I have two 3x3 arrays. One of them indicates if an element is black (let's say 0's - white, 1's black) and another what is the cost of an element. Is there a nice way to get indices of for example all elements that are black and their price is higher than certain value? I know I can use np.where() to select from one array, but how to do it on two (if they have the same shapes)
我有两个3x3阵列。其中一个表示元素是黑色(让我们说0是白色,1是黑色),另一个是元素成本。有没有一种很好的方法来获得例如所有黑色元素的指数并且它们的价格高于某个值?我知道我可以使用np.where()从一个数组中选择,但如何在两个数组中进行选择(如果它们具有相同的形状)
1 个解决方案
#1
2
Following up on the advice of Psidom and rayryeng, I'll add that the output of np.where
can be stacked to present a list of indices in the readable "coordinate" notation, as shown below
根据Psidom和rayryeng的建议,我将补充说,np.where的输出可以堆叠,以可读的“坐标”表示法显示索引列表,如下所示
import numpy as np
a = np.random.randint(0, 2, size=(3,3))
b = np.random.uniform(0, 10, size=(3,3))
print(a)
print(b)
print(np.where(a & (b > 4)))
print(np.vstack(np.where(a & (b > 4))).T)
Random arrays a
and b
:
随机数组a和b:
[[1 0 0]
[1 1 0]
[0 1 1]]
[[ 4.27082885 4.95718491 5.03538203]
[ 8.41593579 3.17425233 3.99337567]
[ 3.90636291 4.96133978 3.61849744]]
Direct output of np.where
for the two conditions a
nonzero and b>4
:
np.where的直接输出为两个条件a非零且b> 4:
(array([0, 1, 2], dtype=int64), array([0, 0, 1], dtype=int64))
Stacked in a human-friendly way:
以人性化的方式堆叠:
[[0 0]
[1 0]
[2 1]]
#1
2
Following up on the advice of Psidom and rayryeng, I'll add that the output of np.where
can be stacked to present a list of indices in the readable "coordinate" notation, as shown below
根据Psidom和rayryeng的建议,我将补充说,np.where的输出可以堆叠,以可读的“坐标”表示法显示索引列表,如下所示
import numpy as np
a = np.random.randint(0, 2, size=(3,3))
b = np.random.uniform(0, 10, size=(3,3))
print(a)
print(b)
print(np.where(a & (b > 4)))
print(np.vstack(np.where(a & (b > 4))).T)
Random arrays a
and b
:
随机数组a和b:
[[1 0 0]
[1 1 0]
[0 1 1]]
[[ 4.27082885 4.95718491 5.03538203]
[ 8.41593579 3.17425233 3.99337567]
[ 3.90636291 4.96133978 3.61849744]]
Direct output of np.where
for the two conditions a
nonzero and b>4
:
np.where的直接输出为两个条件a非零且b> 4:
(array([0, 1, 2], dtype=int64), array([0, 0, 1], dtype=int64))
Stacked in a human-friendly way:
以人性化的方式堆叠:
[[0 0]
[1 0]
[2 1]]