“Numpy”的版本间差异

来自Shiyin's note
跳到导航 跳到搜索
(9)
第75行: 第75行:
直接将nan数值替换为0
直接将nan数值替换为0


===字符串数组chararray====
===字符串数组====
*dtype='str'
*同时对每个元素操作见这里 https://docs.scipy.org/doc/numpy/reference/routines.char.html

*字符串数组里面直接定位一个元素,用index会报错,用find返回的是一个布尔数组
*字符串数组里面直接定位一个元素,用index会报错,用find返回的是一个布尔数组
:解决办法:用tolist()再用index定位
:解决办法:用tolist()再用index定位

2020年1月7日 (二) 03:48的版本

http://bigsec.net/b52/scipydoc/numpy_intro.html

ndarray

  • shape() #数组的形状,虽然len()可以运行
  • size() #数组的总元素
  • a=np.empty_like(b) #初始化一个和b数组一样shape的空数组
  • 产生序列数组 a=np.arange(20)
  • 合并两个数组 np.append(array1,array2)
  • 选择数组在某个范围之内 sel=np.where((wave < 6800) & (wave > 3800))
  • 利用内循环赋值
 a = [0 for x in range(0, 1000)]  

数组运算

  • clip(a,a_min,a_max)
array(a).clip(a_min.a_max)
  • reduce,reduceat
reduceat 有点复杂 参见[1]
  • unique,sort,sum
a=np.zeros([3,5])+1
np.sum(a,1) #只对多维数组的某一个方向上求和
  • roll #平移
  • array[::-1] 数组倒序
  • np.hpstack: stack数组
  • np.hsplit: split数组
 import numpy as np 
 print "Stacking and splitting array" 
 p = np.array([1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]) 
 q = np.array([2.35, 5.75, 7.75, 3.15]) 
 newa = np.hstack((p, q)) 
 print "newa: ", newa 
 r = np.hsplit(newa,3) # three equally shaped arrays 11 print "Array r:"
  • percentile
wout=np.percentile(flatchain,[16,50,84],0) #flatchain 是二维数组,这是在一个维度上求其分布的范围
  • 按照数值大小分成等份的几个数组
>>> a = np.array([3, 4, 2, 1])
>>> >>> x[np.argpartition(x, 3)]
array([2, 1, 3, 4])
>>> np.partition(a, 3) #可以把3替换为一个数组,比如  (1,3)
array([2, 1, 3, 4]) # that the value of the element in k-th position is in the position it would be in a sorted array
  • 布尔型数组取否运算 (~)

数据类型

  • dtype
dtype=object 比较好用,这样每个元素可以是另外一个数组,可以不等长。合并的时候可以采用 hstack的命令
a1=np.arange(10)
a2=np.arange(20)
a=np.array([a1,a2],dtype=object)
a3=np.hstack(a)
dtype=str 字符串 (只能是一位字符)
dype='S256'
  • astype 装换格式(数组的dtype不能直接修改)
 >>> b = np.array([1.23,12.201,123.1])
 >>> b.dtype
 dtype('float64')
  >>> c = b.astype(int)


  • 可以自定义
>>> t = dtype([('name', str, 40), ('numitems', numpy.int32), ('price',numpy.float32)])
>>> itemz = array([('Meaning of life DVD', 42, 3.14), ('Butter', 13,2.72)], dtype=t)

特殊数值 nan,inf

  • isnan, isinf ,isnull
nan只能用isnan来判断
a=1/np.arange
sel=np.where(np.isinf(a))
  • nan_to_num(x)
直接将nan数值替换为0

字符串数组=

  • 字符串数组里面直接定位一个元素,用index会报错,用find返回的是一个布尔数组
解决办法:用tolist()再用index定位

多维数组

  • 极值
Ha是是个二维map
Hamax=Ha.max()
xmax,ymax=np.unravel_index(np.argmax(Ha, axis=None), Ha.shape) #极值位置
  • 降维 Ha.flatten()
  • Ha.reshape(-1) # 也可以达到降维的效果

格式输出

x = np.random.random(10)
np.set_printoptions(precision=3, suppress=True):
print(x)
print(np.array_str(x, precision=2))
np.array2string(x, formatter={'float_kind':'{0:.3f}'.format})
print(np.vectorize("%.2f".__mod__)(x))
  • 另外一个方法
def ndprint(a, format_string ='{0:.2f}'):
   print [format_string.format(v,i) for i,v in enumerate(a)]

叠加标准输出:%r 不换行 %n 换行

for n in range(30):
   sys.stdout.write("\r[{0}{1}]".format('#' * n, ' ' * (30 - n))) 
for n in range(30):
   sys.stdout.write("\n[{0}{1}]".format('#' * n, ' ' * (30 - n)))

简单文件存取

  • ndarray.tofile(self, fid, sep=”“, format=”%s”)
数组的简单存取,比较方便可以用于多维数组(二进制格式)
  • np.load(fname):

fname:文件,以.npy为扩展名,压缩扩展名为.npz

  • np.save(fname,array)
  • numpy.fromfile(file, dtype=float, count=-1, sep=)
  • np.loadtxt(frame,dtype = np.float,delimiter = None,unpack = False)
  • numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘)
可以把一个数组一次性写入某个文件,但是第一个参数貌似必须是文件名,而且不能续写,写完后文件就被关闭。只能最多是2维数组

vectorize

  • 可以将只能对数值计算的函数,变成可以对数组计算,比如积分
import scipy.integrate as integrate
  
    vec_expint=np.vectorize(expint) 
def expint(t1,t2):
    return integrate.quad(CSFH,t1,t2)[0]

随机数

  • random.rand(20,20)