Numpy 3

Fancy Indexing

In [ ]:
import numpy as np

x = np.arange(16)
x
In [ ]:
x[3]
In [ ]:
x[3:9]
In [ ]:
x[3:9:2]
In [ ]:
[x[3], x[5], x[7]]
In [ ]:
ind = [3, 5, 7]
x[ind]
In [ ]:
ind = np.array([[0, 2], [1, 3]])
x[ind]

Fancy Indexing 应用在二维数组

In [ ]:
X = x.reshape(4, -1)
X
In [ ]:
row = np.array([0, 1, 2])
col = np.array([1, 2, 3])
X[row, col]
In [ ]:
X[0, col]
In [ ]:
X[:2, col]
In [ ]:
col = [True, False, True, True]
In [ ]:
X[0, col]

numpy.array 的比较

In [ ]:
x
In [ ]:
x < 3
In [ ]:
x > 3
In [ ]:
x <= 3
In [ ]:
x >= 3
In [ ]:
x == 3
In [ ]:
x != 3
In [ ]:
2 * x == 24 - 4 * x
In [ ]:
X < 6

使用 numpy.array 的比较结果

In [ ]:
np.count_nonzero( x <= 3)
In [ ]:
np.sum(x <= 3)
In [ ]:
np.sum(X % 2 == 0, axis=0)
In [ ]:
np.sum(X % 2 == 0, axis=1)
In [ ]:
np.any(x == 0)
In [ ]:
np.any(x < 0)
In [ ]:
np.all(x > 0)
In [ ]:
np.all(x >= 0)
In [ ]:
np.all(X > 0, axis=1)
In [ ]:
np.sum((x > 3) & (x < 10))
In [ ]:
np.sum((x > 3) && (x < 10))
In [ ]:
np.sum((x % 2 == 0) | (x > 10))
In [ ]:
np.sum(~(x == 0))

比较结果和Fancy Indexing

In [ ]:
x < 5
In [ ]:
x[x < 5]
In [ ]:
x[x % 2 == 0]
In [ ]:
X[X[:,3] % 3 == 0, :]

更多numpy的使用方式

关于numpy比较结果的逻辑组合

In [ ]:
import numpy as np
x = np.arange(16)
x

课程中使用的方式

In [ ]:
np.sum((x < 3) | (x > 10))
In [ ]:
np.sum((x > 3) & (x < 10))
In [ ]:
np.sum(~(x > 3))

另外的方式,logical_andlogical_or

In [ ]:
np.logical_or(x < 3, x > 10)
In [ ]:
np.sum(np.logical_or(x < 3, x > 10))
In [ ]:
np.logical_and(x > 3, x < 10)
In [ ]:
np.sum(np.logical_and(x > 3, x < 10))
In [ ]:
np.logical_not(x > 3)
In [ ]:
np.sum(np.logical_not(x > 3))



猜你喜欢

转载自blog.csdn.net/qq_27384769/article/details/80914543
今日推荐