“Numpy”的版本间差异

来自Shiyin's note
跳到导航 跳到搜索
第39行: 第39行:
*dtype
*dtype
:dtype=object 比较好用
:dtype=object 比较好用
:dtype=str 字符串
:dtype=str 字符串 (只能是一位字符)
:dype='S256'
*astype 装换格式
*astype 装换格式
>>> b = np.array([1.23,12.201,123.1])
>>> b = np.array([1.23,12.201,123.1])

2019年6月17日 (一) 14:28的版本

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

ndarray

  • shape() #数组的形状,虽然len()可以运行
  • size() #数组的总元素
  • a=np.empty_like(b) #初始化一个和b数组一样shape的空数组
  • a=np.empty(100,dtype=object) # 数组的元素是object,就可以赋值不同的类型
这样每个元素可以是另外一个数组,可以不等长。合并的时候可以采用 hstack的命令
  • 产生序列数组 a=np.arange(20)
  • 合并两个数组 np.append(array1,array2)
  • 选择数组在某个范围之内 sel=np.where((wave < 6800) & (wave > 3800))
  • 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 是二维数组,这是在一个维度上求其分布的范围


数据类型

  • dtype
dtype=object 比较好用
dtype=str 字符串 (只能是一位字符)
dype='S256'
  • astype 装换格式
 >>> 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)

多维数组

  • 极值
Ha是是个二维map
Hamax=Ha.max()
xmax,ymax=np.unravel_index(np.argmax(Ha, axis=None), Ha.shape) #极值位置
  • 降维 Ha.flatten()

格式输出

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.savetxt
可以把一个数组一次性写入某个文件,但是第一个参数貌似必须是文件名,而且不能续写,写完后文件就被关闭。只能最多是2维数组
  • ndarray.tofile ndarray.fromfile
数组的简单存取,比较方便可以用于多维数组

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)