import numpy as np
x = np.arange(16)
x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
x[3]
3
x[3:5]
array([3, 4])
x[3:9:2]
array([3, 5, 7])
[x[3], x[5], x[7]]
[3, 5, 7]
ind = [3, 5, 7]
x[ind]
array([3, 5, 7])
ind = np.array([[0, 2], [1, 3]])
x[ind]
array([[0, 2],
[1, 3]])
X = x.reshape(4, -1)
X
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
row = np.array([0, 1, 2])
col = np.array([1, 2, 3])
X[row, col]
array([ 1, 6, 11])
X[0, col]
array([1, 2, 3])
X[:2, col]
array([[1, 2, 3],
[5, 6, 7]])
col = [True, False, True, True]
X[0, col]
array([0, 2, 3])
X[1:3, col]
array([[ 4, 6, 7],
[ 8, 10, 11]])
x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
x < 3
array([ True, True, True, False, False, False, False, False, False,
False, False, False, False, False, False, False], dtype=bool)
x > 3
array([False, False, False, False, True, True, True, True, True,
True, True, True, True, True, True, True], dtype=bool)
x <= 3
array([ True, True, True, True, False, False, False, False, False,
False, False, False, False, False, False, False], dtype=bool)
x >= 3
array([False, False, False, True, True, True, True, True, True,
True, True, True, True, True, True, True], dtype=bool)
x == 3
array([False, False, False, True, False, False, False, False, False,
False, False, False, False, False, False, False], dtype=bool)
x != 3
array([ True, True, True, False, True, True, True, True, True,
True, True, True, True, True, True, True], dtype=bool)
2 * x == 24 - 4 * x
array([False, False, False, False, True, False, False, False, False,
False, False, False, False, False, False, False], dtype=bool)
X < 6
array([[ True, True, True, True],
[ True, True, False, False],
[False, False, False, False],
[False, False, False, False]], dtype=bool)
x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
np.count_nonzero( x <= 3)
4
np.sum(x <= 3)
4
np.sum(X % 2 == 0, axis=0)
array([4, 0, 4, 0])
np.sum(X % 2 == 0, axis=1)
array([2, 2, 2, 2])
np.any(x == 0)
True
np.any(x < 0)
False
np.all(x > 0)
False
np.all(x >= 0)
True
np.all(X > 0, axis=1)
array([False, True, True, True])
np.sum((x > 3) & (x < 10))
6
np.sum((x > 3) && (x < 10))
File "", line 1
np.sum((x > 3) && (x < 10))
^
SyntaxError: invalid syntax
np.sum((x % 2 == 0) | (x > 10))
11
np.sum(~(x == 0))
15
x < 5
array([ True, True, True, True, True, False, False, False, False,
False, False, False, False, False, False, False], dtype=bool)
x[x < 5]
array([0, 1, 2, 3, 4])
x[x % 2 == 0]
array([ 0, 2, 4, 6, 8, 10, 12, 14])
X
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
X[X[:,3] % 3 == 0, :]
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
X数组为
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
我们要查找,每行的第三列能被3整除的行
X[X[:,3] % 3 == 0, :]
输出
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
解释
分成两部分看X[:,3] % 3 == 0
为行索引的条件,:
为列索引的条件
先看行,X[:,3]
的意思是取所有的行,列取索引下标为3的列
对3取模为0的是,数字为3,15,所在的行。
再看列部分,列部分
liuyubobobo老师的《Python3入门机器学习_经典算法与应用》