在Python中合并索引数组

8
假设我有两个形式为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,它只适用于结构化数组或 recarrays,因此有一些小问题。

首先你需要对结构化数组有至少一定的了解。如果你还不熟悉,请查看这里

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”字段更改为整数。


1
谢谢您这个富有见地的回复。因为我的愚笨,是否有一种简单的方法将结构体数组转换为ndarray?感谢。 - leon
@leon - 这是一种方法(使用示例中的“join”数组...):join.view(np.float).reshape((join.size,3))希望能有所帮助! - Joe Kington
1
这实际上不起作用,因为第一列被转换为整数。这就是我之前问的原因。 - leon
1
@leon - 哎呀!我测试了它,但是我把所有东西都设成了浮点数……嗯……据我所知,没有一种通用的方法可以将混合类型结构化数组(例如 int 和 float)转换回统一数据类型的 2d numpy 数组……也许最好将“key”恢复为浮点数?在浮点数基础上进行连接是有风险的,但应该能让您将事物视为统一的 2d 数组……不过这不是一个很好的答案…… - Joe Kington
2
这虽然不太美观,但即使混合了dtype,它也能正常工作... np.vstack([join[name] for name in join.dtype.names]).T - Joe Kington

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接