合并在Python索引数组 [英] merging indexed array in Python

查看:370
本文介绍了合并在Python索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有形式两个numpy的阵列

Suppose that I have two numpy arrays of the form

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

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

有没有合并它们,这样我有一个有效的方法。

is there an efficient way to merge them such that I have

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

我可以使用搜索找到的索引实现一个简单的函数,但这不是优雅和潜在低效很多阵列和大尺寸的。任何指针AP preciated。

I can implement a simple function using search to find the index but this is not elegant and potentially inefficient for a lot of arrays and large dimensions. Any pointer is appreciated.

推荐答案

请参见 numpy.lib .recfunctions.join_by

它仅适用于结构化数组或recarrays,所以有几个扭结。

It only works on structured arrays or recarrays, so there are a couple of kinks.

首先,你需要至少在一定程度熟悉结构阵列。见 href=\"http://docs.scipy.org/doc/numpy/user/basics.rec.html\">。

First you need to be at least somewhat familiar with structured arrays. See here if you're not.

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)

希望帮助!

EDIT1:添加例如
EDIT2:真的不应该与花车加入...更改'键'字段为int

Added example Really shouldn't join with floats... Changed 'key' field to an int.

这篇关于合并在Python索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆