如何在python中合并和求和重复项?

时间:2016-03-12 18:07:37

标签: python numpy

我有一个numpy数组:

   [2016-10-20 00:00:00, 6, 17],
   [2016-10-20 00:00:00, 0, 21],
   [2017-09-11 00:00:00, 7, 22],
   [2017-09-11 00:00:00, 5, 30],
   [2017-09-11 00:00:00, 2, 40]

是否有一种简单的方法可以合并具有相同日期的行并总结属于同一日期的值?

对于上面的示例,它应该如下所示:

   [2016-10-20 00:00:00, 6, 38],
   [2017-09-11 00:00:00, 14, 92]

1 个答案:

答案 0 :(得分:4)

我建议使用pandas

import pandas as pd

d = pd.DataFrame([
    ['2016-10-20 00:00:00', 6, 17],
    ['2016-10-20 00:00:00', 0, 21],
    ['2017-09-11 00:00:00', 7, 22],
    ['2017-09-11 00:00:00', 5, 30],
    ['2017-09-11 00:00:00', 2, 40]
])

d.groupby([0]).aggregate(sum)

#                       1   2
# 0
# 2016-10-20 00:00:00   6  38
# 2017-09-11 00:00:00  14  92

请注意pandas.DataFrame accepts a numpy array as input