Return the elements of an array that satisfy some condition.
Parameters
condition [array_like]
An array whose nonzero or True entries indicate the elements of arr
to extract.
arr [array_like]
Returns
extract [ndarray]
Rank 1 array of values from arr where condition is True.
选出a
中满足条件condition
的元素,形成新的array
,等价于:extractis equivalent to arr[condition]
.
这里的condition
是一个和arr
具有相同shape的array,其元素和arr
的元素一一对应,arr
中的元素如果在condition
中对应的元素为True,则被保留,为False,则被舍弃.
在numpy中,像这里的condition
表征数组哪些元素有效的boolean数组被定义为mask
示例
选出除以3余数为0的元素
#Input array of the same size as condition.
>>>import numpy as np
>>>arr = np.arange(12).reshape((3, 4))
>>>print(arr)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
condition = np.mod(arr, 3)==0
np.extract(condition, arr)
array([0, 3, 6, 9])
等价于
arr[np.mod(arr,3)==0]
array([0, 3, 6, 9])