import numpy as np
#### 生成ndarray数组对象(zeros,ones,eye)
- np.zeros(5) == np.zeros((5,)) #意思都是创建numpy的一维数组,该例的答案是[0,0,0,0,0],(5,)表示第一个参数
- a=random.randn(2,3) # 创建 randn(size) 服从 X~N(0,1) 的正态分布随机数组
- b=random.randint([low,high],size) #创建在[low, high]间的数组;a=random.randint(100,200,(3,3))
#### 将其他对象转化为ndarray数组
- numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0) #接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。
- numpy.asarray((1,2,3)) #将元组变为ndarray
- numpy.fromiter(iterable, dtype, count=-1) #从可迭代对象中建立 ndarray 对象,返回一维数组
- 例:
import numpy as np
# 使用 range 函数创建列表对象
list=range(5)
it=iter(list)
# 使用迭代器创建 ndarray
x=np.fromiter(it, dtype=float)
print(x)
#### numpy从数值范围生成数组
- numpy.arange(start, end, step, dtype)
- numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) #创建一个一维数组,数组是一个等差数列构成的
- np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None) #函数用于创建一个于等比数列
#### Numpy--结构化数据类型
- numpy中支持很多数据类型,比如int,float等,也可以自己使用dtype()自己新定义一个数据类型,这个数据类型可能类似于C中的数据结构。
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
那么相当于c中:
struct student{
char name[20];
int age;// 8位整型数
float marks // 32位浮点数
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print(a) # 数组的 dtype 为 int8(一个字节
x = np.array([1,2,3,4,5], dtype = np.int8)
print (x.itemsize)
#### numpy高级索引 数组可以由整数数组索引、布尔索引及花式索引
- 整数数组索引
q = np.array([[1,2], [3,4], [5,6]])
y = q[[0,1,2], [0,1,0]]
print y
#[1, 4, 5]
2.布尔索引
import numpy as np
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
print ('大于 5 的元素是:')
print (x[x > 5])
#[ 6 7 8 9 10 11]
#过滤数组中的非复数元素
a = np.array([1, 2+6j, 5, 3.5+5j])
print (a[np.iscomplex(a)])
#[2.0+6.j 3.5+5.j]
3.花式索引
import numpy as np
x=np.arange(32).reshape((8,4))
print (x[np.ix_([1,5,7,2],[0,3,1,2])])
'''
传入多个索引数组(要使用np.ix_)
[[ 4 7 5 6]
[20 23 21 22]
[28 31 29 30]
[ 8 11 9 10]]
'''
- numpy迭代器****
- **np.nditer(order, op_flags, flags) ** #默认行遍历优先,order遍历顺序,op_flags控制列表是否可读写,flags外部循环
#1
a = np.arange(6).reshape(2,3)
for x in np.nditer(a.T):
print (x, end=", " )
for x in np.nditer(a.T.copy(order='C')):
print (x, end=", " )
#输出(俩个):0, 1, 2, 3, 4, 5,
#可见a的存储与a.T一样在内存中
#2
a = np.arange(0,60,5)
a = a.reshape(3,4)
for x in np.nditer(a, op_flags=['readwrite']):
x[...]=2*x
print ('修改后的数组是:')
修改后的数组是:
[[ 0 10 20 30]
[ 40 50 60 70]
[ 80 90 100 110]]
#3
a = np.arange(0,60,5)
a = a.reshape(3,4)
print ('原始数组是:')
print ('修改后的数组是:')
for x in np.nditer(a, flags = ['external_loop'], order = 'F'):
print (x, end=", " )
原始数组是:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
修改后的数组是:
[ 0 20 40], [ 5 25 45], [10 30 50], [15 35 55],