简体   繁体   English

在数组中找到与另一个数组python中的值相对应的行

[英]Numpy finding rows in array that correspond to values in another array python

I have the following arrays: 我有以下数组:

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']])

and I want to get the following: 我想得到以下内容:

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

How do I do this?? 我该怎么做呢??

I think this should work, or at least get you in the right direction. 我认为这应该可行,或者至少可以使您朝正确的方向发展。

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

read about np.where: http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html 阅读有关np.where的信息: http ://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

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

Take the first row ( next() ), where the first element equals an element e1 of arr1 . 取第一行( next() ),其中第一个元素等于arr1的元素e1

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

Out: 出:

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

The numpy_indexed package (disclaimer: I am its author) has functionality to address this problem efficiently. numpy_indexed软件包(免责声明:我是它的作者)具有有效解决此问题的功能。 You can think of it as a vectorized equivalent of list.index. 您可以将其视为list.index的向量等效项。 Should be in numpy itself if you ask me; 如果你问我的话,应该是麻木的。 maybe in a future version! 也许在将来的版本中!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM