Numpy

Numpy

   numpy有自己的数据类型 np.ndarray(数组)

将python列表转换为数组:

  python的列表本质是三个指针和三个整数的对象,对于数值运算而言是比较浪费cpu和内存的。因此numpy提供了新的数据类型

L = [1, 2, 3, 4, 5]
a = np.array(L)

转换数组a的行列数: 

  a.shape 改变原数组的数据显示形式 其内存位置及存储顺序没发生改变,

  a.reshape 会返回新的显示视图,-1 自动计算另一个维度。a, 和 b是共享同一个内存空间。a, b任何一个做更改都另一个都跟着改变

a.shape = 3, 2
a.shape = 3, -1
b = a.reshape(2, -1)

数据类型的查看及转换: 

  数组转换时可以直接指定数据类型,astype是安全转换数据类型

a.dtype
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float)
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.complax)
s = np.astype(np.int)

# 错误写法: b.dtype = np.int

常用的创建函数

  arange不止支持整型还支持其他数据类型, linspace 从1开始到10 等差取10个 endpoint 为false不包含终止值, logspace起始值是10**1 终止值是10**2等比取20个 base默认为10

np.arange(1, 10, 0.5)
np.linspace(1, 10, 10,endpoint=False)
np.logspace(1, 2, 20, endpoint=True,base=10)
s = 'abcd'
np.fromstring(s, dtype=np.int8) # [97, 98, 99, 100] 将字符串转成整型数的数组

数组的存取

  一维数组中的存取和python的list是一样,对于数组a  和 切片的数组b是共享内存的 

a = np.arange(0, 60, 10).reshape(1, -1) + np.arange(6)
a[(1, 2, 3, 4), (2, 3, 4, 5)]
a[3:, [0, 2, 5]]  # 第三行开始的 0, 2, 5列

随机数的生成

  np.random.rand(10) 从0 - 1 随机取10个数

a = np.random.rand(10)
b = a[a > 0.5]
a[a > 0.5] = 0.5
原文地址:https://www.cnblogs.com/bianjing/p/10034109.html