Numpy在数组中查找与另一个数组python中的值对应的行

时间:2015-07-15 21:24:56

标签: python arrays numpy indexing

我有以下数组:

arr1 = np.array(['x','y','z'])

arr2 = np.array(['y','a','b','z','c','x'])

arr3 = np.array([['y','d1','d2','d3'],
                 ['a','d4','d5','d6'],
                 ['b','d7','d8','d9'],
                 ['z','d10','d11','d12'],
                 ['c','d13','d14','d15'],
                 ['x','d16','d17','d18']])

我希望得到以下内容:

answer = np.array([[x,d16,d17,d18],
                   [y,d1,d2,d3]
                   [z,d10,d11,d12]])

我该怎么做?

4 个答案:

答案 0 :(得分:0)

我认为这应该有用,或者至少让你朝着正确的方向前进。

idxs = np.where( arr3[:,0] == arr1 )
answer = arr3[idxs, :]

了解np.where:http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

答案 1 :(得分:0)

inds = [ where( arr3[:,0] == val)[0] for val in arr1 ]
inds = [ i[0] for i in inds if i.size ] 
answer = arr3[inds]

答案 2 :(得分:0)

取第一行(next()),其中第一行等于e1的元素arr1

array([
    next(row3 for row3 in arr3 if row3[0]==e1)
      for e1 in arr1])

输出:

array([['x', 'd16', 'd17', 'd18'],
       ['y', 'd1', 'd2', 'd3'],
       ['z', 'd10', 'd11', 'd12']], 
  dtype='|S3')

答案 3 :(得分:0)

numpy_indexed包(免责声明:我是其作者)具有有效解决此问题的功能。您可以将其视为list.index的向量化等价物。如果你问我,应该是numpy本身;也许在将来的版本中!

import numpy_indexed as npi
answer = arr3[npi.indices(arr3[:,0], arr1)]