This question already has answers here:
Pandas group-by and sum
                                
                                    (6个答案)
                                
                        
                                去年关闭。
            
                    
我有一个包含多个重复实例的数据框,按日期排序。看起来像这样:

python - 在Python中合并行并按日期对值求和-LMLPHP

我正在尝试按日期合并行以匹配“关键字”,并对“视图”计数求和。

我想要获得的结果如下:

python - 在Python中合并行并按日期对值求和-LMLPHP

谁能暗示我如何在Python中实现?谢谢。

数据框:

 df = pd.DataFrame([["3/8/14", "adapter", 2], ["3/8/14", "adapter", 5], ["3/8/14", "charger", 1],
                   ["13/8/14", "adapter", 1], ["13/8/14", "battery-case", 0]],
                  columns=['Date', 'Keyword', 'Views'])

最佳答案

你想要一个groupby!

import pandas as pd

df = pd.DataFrame([["3/8/14", "adapter", 2], ["3/8/14", "adapter", 5], ["3/8/14", "charger", 1],
                   ["13/8/14", "adapter", 1], ["13/8/14", "battery-case", 0]],
                  columns=['Date', 'Keyword', 'Views'])
print df

#       Date       Keyword  Views
# 0   3/8/14       adapter      2
# 1   3/8/14       adapter      5
# 2   3/8/14       charger      1
# 3  13/8/14       adapter      1
# 4  13/8/14  battery-case      0

df2 = df.groupby(['Date','Keyword'],as_index=False).agg({'Views': 'sum'})

print df2

#       Date       Keyword  Views
# 0  13/8/14       adapter      1
# 1  13/8/14  battery-case      0
# 2   3/8/14       adapter      7
# 3   3/8/14       charger      1

08-28 12:03