在Python中合并索引数组

8 投票
1 回答
3820 浏览
提问于 2025-04-15 22:23

假设我有两个numpy数组,格式如下:

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

y = [[0,-5]
     [1,0]
     [2,5]
     [5,20]
     [6,25]]

有没有什么高效的方法可以把它们合并成这样:

xmy = [[0, NaN, -5  ]
       [1, 2,    0  ]
       [2, 4,    5  ]
       [3, 6,    NaN]
       [4, NaN,  NaN]
       [5, 10,   20 ]
       [6, NaN,  25 ]

我可以用一个简单的函数来搜索找到索引,但这样做不够优雅,而且对于很多数组和大尺寸的情况可能效率不高。任何建议都很感谢。

1 个回答

10

请查看 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

这段代码的输出是:

(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)

希望这对你有帮助!

编辑1:添加了示例
编辑2:实际上不应该用浮点数来连接... 把'key'字段改成了整数。

撰写回答