import numpy as np
A 和 B 数组顺序良好。
A = np.array(['a','b','c','d','e'])
B = np.array([5,7,3,9,11])
C = np.array(['a','b','k','j','p','x'])
对于数组C的每个元素,如果该元素在A中,则从与B相同位置的B中获取值。如果不在A中,则写入np.nan。
预期结果是:
result = np.array([5,7,na,na,na,na])
在 numPy 中最简单的方法是怎样的?
最佳答案
您可以使用np.in1d(C, A)
确定 C
是否在 A
中。
In [110]: np.in1d(C, A)
Out[115]: array([ True, True, False, False, False], dtype=bool)
然后使用np.where
从B
或np.nan
中选择所需的值:
In [116]: np.where(np.in1d(C, A), B, np.nan)
Out[116]: array([ 5., 7., nan, nan, nan])
np.where(cond, B, np.nan)
返回与 bool 数组 cond 形状相同的数组。
如果 cond
中的相应值为 True,则返回的数组从 B
获取值,否则为 np.nan
。
如果 len(C) > len(B)
,并且您希望最终数组的最后一个 len(C) 包含
值,那么你可以使用:NaN
-len(B)
N = len(B)
result = np.full(len(C), np.nan)
result[:N] = np.where(np.in1d(C[:N], A), B, np.nan)
关于python - 从 NumPy 数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408914/