where
将np.arange(10)数组中奇数替换成-1
语法:
-
np.where(判断条件,满足条件返回值,不满足条件返回值)
将满足条件的值返回为新的数组
-
array[np.where(判断条件)]
import numpy as np
a = np.arange(10)
x = np.where(a%2!=0,-1,a)
x
输出结果:
array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
切片
从数组的对角线取值并生成一个新的数组
b = np.arange(16).reshape(4,4)
b
输出结果:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
b[np.arange(4), np.arange(4)]
输出结果:
array([ 0, 5, 10, 15])
取出数组 b(0,0)(1,2)(3,2)中的值
b = np.arange(16).reshape(4,4)
b[0,0]
输出结果:
0
b[1,2]
输出结果:
6
b[3,2]
输出结果:
14
取出多行数据(2-3行数据)
b = np.arange(16).reshape(4,4)
b[1:3]
输出结果:
array([[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
取出1-5行第8列大于30的数
c = np.arange(72).reshape(8,9)
c[:5,7][np.where(d>30)]
输出结果:
array([34, 43])