目录
1.创建数组
(1)创建数组方法:array
(1)import numpy as np
a = np.array([1,2,3])
print (a)
(2)import numpy as np
a = np.array([[1, 2], [3, 4]])
print (a)
输出结果如下:
(1)[1 2 3]
(2)[[1 2]
[3 4]]
(2) 创建内容全为0或者全为1的数组
(1)import numpy as np
# 设置类型为整数,数组形状为2行3列
y = np.zeros((2,3), dtype = int)
print(y)
(1)import numpy as np
# 默认类型会将数据变为浮点类型,数组形状为2行3列
y = np.ones((2,3))
print(y)
输出结果如下:
(1)[[0 0 0]
[0 0 0]]
(2)[[1. 1. 1.]
[1. 1. 1.]]
(3)创建有规律的数组
(1)import numpy as np
x = np.arange(5)
print (x)
(2)import numpy as np
#设置了起始值、终止值及步长
x = np.arange(10,20,2)
print (x)
输出结果如下:
(1)[0 1 2 3 4]
(2)[10 12 14 16 18]
2.数组的切片及索引
(1)一维数组的切片
import numpy as np
a = np.arange(10)
b = a[2:7:2] # 从索引 2 开始到索引 7 停止,间隔为 2
print(a,b)
输出结果如下:
[0 1 2 3 4 5 6 7 8 9] [2 4 6]
(2)简单索引
import numpy as np
#x为3行2列的数组,y中是获取了数组中 (0,0),(1,1) 和 (2,0) 位置处的元素
x = np.array([[1, 2], [3, 4], [5, 6]])
y = x[[0,1,2], [0,1,0]]
print(x)
print (y)
输出结果如下:
(3)布尔索引
import numpy as np
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
#布尔索引
y = x[x > 5]
print (x)
print (y)
输出结果如下:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[ 6 7 8 9 10 11]
3.操作单个数组方法:reshape
import numpy as np
a = np.arange(8)
print (a)
b = a.reshape(4,2)
print (b)
输出结果如下:
[0 1 2 3 4 5 6 7] #a
[[0 1]
[2 3]
[4 5]
[6 7]] #b