在Python中合并索引数组

2024-03-29 01:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

有没有一种有效的方法把它们合并到我

^{pr2}$

我可以使用search来实现一个简单的函数来查找索引,但这并不优雅,而且对于很多数组和大维度来说可能效率低下。任何指针都可以。在


Tags: 方法函数numpysearch数组nan形式效率
1条回答
网友
1楼 · 发布于 2024-03-29 01:35:49

numpy.lib.recfunctions.join_by

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

首先,您至少需要对结构化数组有所了解。如果不是,请参阅here。在

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

该输出:

^{2}$

希望有帮助!在

编辑1:添加示例 编辑2:真的不应该加入浮动。。。将“key”字段更改为int

相关问题 更多 >