【问题标题】:Python: For a 2D array, sum the 2nd col of the non-unique elements in first col?Python:对于二维数组,将第一列中非唯一元素的第二列求和?
【发布时间】:2023-02-14 00:43:11
【问题描述】:

嗨请你帮我解决这个问题。

我有一个排序的 2D numpy 数组,在第一个列中有一些重复的元素,我想创建一个新的排序数组,其中第二列对重复的元素求和。

例如。我有一个 2 x 4 数组:

Y = np.array([14.0, 100], [15.0, 130], [15.0, -90], [16.0, 60])

我想要以下 2 x 3 数组:

Z = np.array([14.0, 100], [15.0, 40], [16.0.60])

我正在查看 reduce/map/lambda,但还没有开始工作。

【问题讨论】:

    标签: python numpy


    【解决方案1】:
    import numpy as np
    
    y = np.array(([14.0, 100], [15.0, 130], [15.0, -90], [16.0, 60]))
    
    u=np.unique(y[:,0])
    sums=[np.sum(y[:,1],where=y[:,0]==a) for a in u]
    
    counts=np.stack([u,sums],axis=1)
    print(counts)
    

    这给出了以下结果:

    [[ 14. 100.][ 15.  40.][ 16.  60.]]
    

    【讨论】:

      【解决方案2】:

      使用np.unique + np.split

      u, idx = np.unique(Y[:, 0], return_index=True)
      Z = np.column_stack([u, [a.sum() for a in np.split(Y[:,1], idx)[1:]]])
      

      array([[ 14., 100.],
             [ 15.,  40.],
             [ 16.,  60.]])
      

      【讨论】:

        猜你喜欢
        • 2016-03-24
        • 2013-09-25
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多