1. 一维数组
切片
a = np.arange(10)
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[5]
# 5
a[2:6]
# array([2, 3, 4, 5])
a[0:3] = 100
a # 原数组发生改变
array([100, 100, 100, 3, 4, 5, 6, 7, 8, 9])
# 如果不想对原来的 array 进行修改,我们可以把选取的部分 copy 出来
a_slice = a[0:5].copy()
a_slice
# array([100, 100, 100, 3, 4])
2. 多维数组
切片
def f(x,y):
return 4 * x + y
b = np.fromfunction(f,(3,2),dtype=int)
b
# array([[0, 1],
[4, 5],
[8, 9]])
# derive from locations of the matrix
#[[00],[01],[10],[11],[20],[21]]
#通过函数来建矩阵
b[1]
# array([4, 5])
b[1][0] #等价于b[1,0]
# 4
b[:, 1] # 所有行&第二列
# array([1, 5, 9])
b[1:3,1] # 第二行到第三行&第二列
# array([5, 9])
迭代
c = np.zeros ([5,5])
column_length = c.shape[1] # 列的个数;shape[0]行的个数
# 5
for i in range(column_length):
c[i] = i
print(c[i])
#[0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1.]
[2. 2. 2. 2. 2.]
[3. 3. 3. 3. 3.]
[4. 4. 4. 4. 4.]
索引
week_days=np.array(['Monday','Tuesday','Wednesday','Thursday','Friday'])
work_time=np.round(np.random.randn(5,5)+8.0, 2)
# 小数点后保持两位
# round() 方法返回浮点数x的四舍五入值。
work_time
# array([[10.12, 6.86, 8.21, 8.17, 9.03],
[ 8.64, 8.7 , 9.13, 8.53, 7.78],
[ 5.79, 8.12, 7.88, 8.59, 8.94],
[ 8.46, 7.17, 7.1 , 8.25, 7.06],
[ 7.46, 6.69, 9.17, 6.97, 8.34]])
week_days == 'Tuesday'
# array([False, True, False, False, False])
work_time.T[week_days == 'Tuesday']
# array([[6.86, 8.7 , 8.12, 7.17, 6.69]])