如果第一个与2d数组匹配,则将其与第二个值相加

时间:2020-07-20 13:00:58

标签: python arrays numpy

所以我有一个numpy数组:

array([[2.   , 0.125],
       [3.   , 0.125],
       [3.   , 0.125],
       [4.   , 0.125],
       [4.   , 0.125],
       [5.   , 0.125],
       [5.   , 0.125],
       [6.   , 0.125]])

如果第一个匹配,我想将这些条目合并在一起:

array([[2.   , 0.125],
       [3.   , 0.25 ],
       [4.   , 0.25 ],
       [5.   , 0.25 ],
       [6.   , 0.125]])

他们是一种无需循环即可解决此问题的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以为此使用numpy.bincount

import numpy as np

a = np.array([[2.   , 0.125],
              [3.   , 0.125],
              [3.   , 0.125],
              [4.   , 0.125],
              [4.   , 0.125],
              [5.   , 0.125],
              [6.   , 0.125],
              [5.   , 0.125]],
)
def groupby(a):
    """
    >>> groupby(a)
    array([[2.   , 0.125],
           [3.   , 0.25 ],
           [4.   , 0.25 ],
           [5.   , 0.25 ],
           [6.   , 0.125]])
    """
    values, indices = np.unique(a[:, 0], return_inverse=True)
    sum = np.bincount(indices, weights=a[:, 1])
    return np.c_[values, sum]

答案 1 :(得分:0)

如果考虑使用其他软件包,pandas是一个不错的选择:

pd.DataFrame(a).groupby([0])[1].sum()

输出:

0
2.0    0.125
3.0    0.250
4.0    0.250
5.0    0.250
6.0    0.125
Name: 1, dtype: float64