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

标签 python dataframe merge rows

<分区>

我有一个包含多个重复实例的数据框,按日期排序。它看起来像这样:

enter image description here

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

我希望获得的结果如下:

enter image description here

谁能告诉我如何在 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

关于python - 在 Python 中按日期合并行和求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772271/

相关文章:

python - 使用行和列多重索引和给定顺序从表格转换为矩阵

python - 如何不计算用户输入的重复项?

python - 来自嵌套元组的 Pandas Dataframe

mysql - 合并同一数据库的两个版本: duplicate id errors

python - Pandas df.mode 列中每个单元格具有多个值

python - Google App Engine Remote API 无法从本地客户端运行

python - 在 Pandas 中向先前的单元格值添加计数

python - 根据数据的特征是否相交对数据进行分组

python - 使用 Pandas Python 进行透视以获取 bool 值

python - 沿着具有非唯一索引的列连接两个数据框