一、n维数组 ndarray
使用numpy模块建立的数组数据类型为ndarray (n-dimension array)。
可以使用以下命令调用ndarray的属性:
import numpy as np
ndarray = np.array([[1,2,3],[1,2,3]])
print(ndarray.dtype) # 数组元素类型
print(ndarray.item) # 数组元素数据所占空间(字节)
print(ndarray.ndim) # 数组维度
print(ndarray.shape) # 数组形状
print(ndarray.size) # 数组元素个数
二、建立n维数组
1、np.array()
x1 = np.array(shape, dtype = float)
shape:数组形状。
dtype:数据类型,默认:float。
2、np.zeros()
x1 = np.zeros(shape, dtype = float)
3、np.zones()
x1 = np.ones(shape, dtype = float)
4、np.empty()
x1 = np.empty(shape, dtype = float)
5、np.random.randint()
x1 = np.random.randint(low, high = None, size=None, dtype = int)
low:随机数的最小值(包含)。
high:可选项。有则为[low,high);无则为[0,low),随机数范围。
size:数组形状/大小。
dtype:数据类型,默认为:int
6、np.arange()
x1 = np.arange(start, stop, step)
start:起始值(包含),默认为:0。
stop:结束值。
step:相邻元素间距,默认为:1。
7、np.reshape()
x1 = np.reshape(oldshape, newshape)
oldshape:要更改的数组。
newshape:新数组的形状。
三、数组的四则运算
数学中的四则运算符号“+、-、*、/、//、%、**”同样可以运用于Numpy数组。
x = np.array([1,2,3])
y = x + 5 # 以 + 运算为例
四、数组切片与索引
ndarray[start:end:step]
start:起始索引,省略则表示从0开始索引。
end:终止索引,省略则表示到末端的所用元素。
step:索引间隔,默认为 1。
# 切片
ndarray[:n] # 从起始取到第n-1个
ndarray[n:] # 从第0个元素取到最后
ndarray[:-n] # 取得前面列表,不含最后n名
ndarray[-n:] # 取得列表后n名
ndarray[:] # 取得所有元素
ndarray[::n] # 从起始每隔n个元素间隔取到最后
#索引
ndarray[x,y] # 取出第x行,第y列的元素
五、数组合并
x = np.hstack(tup) # 水平合并
x = np.vstack(tup) # 垂直合并
tup:元组tuple(),内容为要垂直合并的两个数组
import numpy as np
x1 = np.random.randint(0,5,(2,3))
x2 = np.random.randint(5,10,(2,3))
x = np.hstack(tup=(x1,x2))
# x = np.vstack(tup=(x1,x2))
print('数组 1 \n{}'.format(x1))
print('数组 2 \n{}'.format(x2))
print('合并结果 \n{}'.format(x))
数组 1
[[2 3 4]
[2 1 2]]
数组 2
[[7 5 9]
[6 5 6]]
合并结果
[[2 3 4 7 5 9]
[2 1 2 6 5 6]]