【问题标题】:merging indexed array in Python在Python中合并索引数组
【发布时间】:2011-02-16 00:37:28
【问题描述】:

假设我有两个 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 ]

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

【问题讨论】:

    标签: python arrays numpy scipy


    【解决方案1】:

    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
    

    这个输出:

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

    【讨论】:

    • 感谢您的富有洞察力的回复。对于我的愚蠢,有没有一种简单的方法可以将结构数组转换为 ndarray?谢谢。
    • @leon - 这是一种方法(在示例中使用“join”数组...):join.view(np.float).reshape((join.size,3)) 希望有帮助!
    • 这实际上不起作用,因为第一列被转换为 int。这就是我问的原因。
    • @leon - 哎呀!我对其进行了测试,但是我将所有内容都作为浮点数...嗯...据我所知,没有一种万能的方法可以将具有混合(例如 int 和浮点数)dtype 的结构化数组转换回 2d numpy统一 dtype 的数组...也许最好将“键”恢复为浮点数?您冒着基于浮点数加入的风险,但它应该让您将事物视为统一的二维数组......但这不是一个很好的答案......
    • 嗯,这很丑陋,但它甚至适用于混合 dtype... np.vstack([join[name] for name in join.dtype.names]).T
    猜你喜欢
    • 1970-01-01
    • 2015-11-11
    • 2018-06-10
    • 2018-05-28
    • 2012-03-21
    • 2020-12-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多