import numpy as np
x = np.arange(10)
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
X = np.arange(15).reshape(5,3)
X
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])
访问
x[2]
2
X[1,1]
4
切片
x[5:]
array([5, 6, 7, 8, 9])
# 行切片,列切片
X[2:4,1:]
array([[ 7, 8],
[10, 11]])
X[2:,0:2]
array([[ 6, 7],
[ 9, 10],
[12, 13]])
# 如果说不关心reshape的定外一个参数,我们可以写成-1,numpy指定推导出这个参数
x.reshape(5,-1)
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
numpy的与运算
X
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])
X+1
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
X*2
array([[ 0, 2, 4],
[ 6, 8, 10],
[12, 14, 16],
[18, 20, 22],
[24, 26, 28]])
np.sin(X)
array([[ 0. , 0.84147098, 0.90929743],
[ 0.14112001, -0.7568025 , -0.95892427],
[-0.2794155 , 0.6569866 , 0.98935825],
[ 0.41211849, -0.54402111, -0.99999021],
[-0.53657292, 0.42016704, 0.99060736]])
NUMPY 中的argsort()
x = np.arange(16)
x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
# 随机打乱
# from random import shuffle
np.random.shuffle(x)
x
array([ 6, 2, 7, 10, 13, 3, 11, 14, 1, 0, 5, 4, 9, 12, 15, 8])
np.argsort(x)
array([ 9, 8, 1, 5, 11, 10, 0, 2, 15, 12, 3, 6, 13, 4, 7, 14],
dtype=int64)
Numpy中的布尔索引
names = np.array(['Bob','Joe','Will', 'Will','Bob','Joe','Will'])
names
array(['Bob', 'Joe', 'Will', 'Will', 'Bob', 'Joe', 'Will'], dtype='<U4')
# 使用np.random模块的randn生成一些正太分部的随即数据
data = np.random.randn(7,4)
data
array([[ 0.03290805, 0.90771856, -0.81345972, 0.46827413],
[ 0.52700879, 0.33853328, -1.20246958, 1.14056211],
[ 0.2077111 , -0.85287939, 0.64753495, 0.51345487],
[ 0.56489484, 0.15367868, 0.38281581, 0.98537961],
[ 0.29369419, 1.19652407, 0.18914402, -0.25025609],
[-0.58819709, -1.03515838, -0.13233965, -0.06189865],
[-1.90031352, 0.81946973, -0.68476672, 0.1286769 ]])
# 假设每个名字对应data数组的一行
names =='Bob'
array([ True, False, False, False, True, False, False])
# 布尔型索引可以应用于数据的筛选
data[names == 'Bob']
array([[ 2.12140159, 0.265584 , -0.73249615, 0.31393966],
[-0.05550636, -0.0832018 , -1.27019383, -0.18444114]])
# 布尔型索引应用于修改值
#选取所有JOE的行,并且全部值赋值为 0
data[names == 'Joe'] = 0
data
array([[ 2.12140159, 0.265584 , -0.73249615, 0.31393966],
[ 0. , 0. , 0. , 0. ],
[-1.1163393 , -0.41695486, -0.48934225, -0.0688788 ],
[ 0.41426097, -0.87294359, 0.33790829, -1.75023062],
[-0.05550636, -0.0832018 , -1.27019383, -0.18444114],
[ 0. , 0. , 0. , 0. ],
[ 1.37574555, 0.74651564, -1.61976615, 0.04435584]])
#选取所有Will的行,并将选取数据的后两列值赋值为 0
data[names == 'Will',2:] = 0
data
array([[ 0.03290805, 0.90771856, -0.81345972, 0.46827413],
[ 0.52700879, 0.33853328, -1.20246958, 1.14056211],
[ 0.2077111 , -0.85287939, 0. , 0. ],
[ 0.56489484, 0.15367868, 0. , 0. ],
[ 0.29369419, 1.19652407, 0.18914402, -0.25025609],
[-0.58819709, -1.03515838, -0.13233965, -0.06189865],
[-1.90031352, 0.81946973, 0. , 0. ]])