在Python中合并索引数组

leo*_*on 6 python arrays numpy scipy

假设我有两个numpy数组的形式

x = [[1,2]
     [2,4]
     [3,6]
     [4,NaN]
     [5,10]]

y = [[0,-5]
     [1,0]
     [2,5]
     [5,20]
     [6,25]]
Run Code Online (Sandbox Code Playgroud)

有没有一种有效的方式来合并它们,就像我一样

xmy = [[0, NaN, -5  ]
       [1, 2,    0  ]
       [2, 4,    5  ]
       [3, 6,    NaN]
       [4, NaN,  NaN]
       [5, 10,   20 ]
       [6, NaN,  25 ]
Run Code Online (Sandbox Code Playgroud)

我可以使用搜索来实现一个简单的函数来查找索引,但这对于许多数组和大尺寸而言并不优雅且可能效率低下.任何指针都很受欢迎.

Joe*_*ton 9

请参阅numpy.lib.recfunctions.join_by

它只适用于结构化数组或重组,因此存在一些问题.

首先,您需要至少熟悉结构化数组.如果你不是,请看这里.

import numpy as np
import numpy.lib.recfunctions

# Define the starting arrays as structured arrays with two fields ('key' and 'field')
dtype = [('key', np.int), ('field', np.float)]
x = np.array([(1, 2),
             (2, 4),
             (3, 6),
             (4, np.NaN),
             (5, 10)],
             dtype=dtype)

y = np.array([(0, -5),
             (1, 0),
             (2, 5),
             (5, 20),
             (6, 25)],
             dtype=dtype)

# You want an outer join, rather than the default inner join
# (all values are returned, not just ones with a common key)
join = np.lib.recfunctions.join_by('key', x, y, jointype='outer')

# Now we have a structured array with three fields: 'key', 'field1', and 'field2'
# (since 'field' was in both arrays, it renamed x['field'] to 'field1', and
#  y['field'] to 'field2')

# This returns a masked array, if you want it filled with
# NaN's, do the following...
join.fill_value = np.NaN
join = join.filled()

# Just displaying it... Keep in mind that as a structured array,
#  it has one dimension, where each row contains the 3 fields
for row in join: 
    print row
Run Code Online (Sandbox Code Playgroud)

这输出:

(0, nan, -5.0)
(1, 2.0, 0.0)
(2, 4.0, 5.0)
(3, 6.0, nan)
(4, nan, nan)
(5, 10.0, 20.0)
(6, nan, 25.0)
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

Edit1:添加了示例Edit2:真的不应该加入浮点数......将'key'字段更改为int.

  • 好吧,这很难看,但它甚至可以使用混合dtype ... np.vstack([join [name] for join.dtype.names]).T (2认同)