使用超过 2 个参数根据其他数组的值对 numpy 数组进行切片
Slice numpy array based on values of other array using more than 2 arguments
这是我当前的代码:
a = np.array(['apples', 'pear', 'oranges', 'grapes', 'apples', 'banana'])
b = np.array([1,2,3,4,5,6])
my_list = ['apples', 'oranges', 'grapes']
如何创建一行代码来 return 以下结果:
result = np.array([1,3,4,5])
该方法必须以my_list为基础,在数组a的基础上对数组b进行切片。
(无论 my_list 的长度如何,它都应该有效)
提前致谢!
您可以使用 np.in1d()
:
进行切片
In [15]: b[np.in1d(a, my_list)]
Out[15]: array([1, 3, 4, 5])
这是我当前的代码:
a = np.array(['apples', 'pear', 'oranges', 'grapes', 'apples', 'banana'])
b = np.array([1,2,3,4,5,6])
my_list = ['apples', 'oranges', 'grapes']
如何创建一行代码来 return 以下结果:
result = np.array([1,3,4,5])
该方法必须以my_list为基础,在数组a的基础上对数组b进行切片。 (无论 my_list 的长度如何,它都应该有效)
提前致谢!
您可以使用 np.in1d()
:
In [15]: b[np.in1d(a, my_list)]
Out[15]: array([1, 3, 4, 5])