我有四列数据,包括:Id
、CreationDate
、Score
和 ViewCount
。
CreationDate
具有以下格式,例如:2011-11-30 19:41:14.960。
我需要按 CreationDate
的年份进行分组,对它们进行计数,对 Score
和 ViewCount
进行求和,并添加到其他列。
我想与 pandas lib 一起使用。
谢谢!
更改之前 - 示例:
Id CreationDate Score ViewCount
0 1 2011-11-30 19:15:54.070 25 1526
1 2 2011-11-30 19:41:14.960 20 601
2 3 2012-11-30 19:42:45.470 36 1015
3 4 2018-11-30 19:44:55.593 8 1941
4 5 2011-11-30 19:53:23.387 11 5053
5 6 2018-11-30 20:04:43.757 25 5123
6 7 2011-11-30 20:08:23.267 53 8945
更改后 - 显示如下数据:
Id CreationDate Score ViewCount
0 1 2011 109 16125
2 3 2012 36 1015
3 4 2018 33 7064
最佳答案
您可以通过 Series.dt.year
将列转换为年份并按 GroupBy.agg
聚合带有聚合函数列的字典,最后添加 DataFrame.reindex
如果需要,列的顺序与原始 DataFrame 中的相同:
#if necessary convert to datetimes
df['CreationDate'] = pd.to_datetime(df['CreationDate'])
df1 = (df.groupby(df['CreationDate'].dt.year)
.agg({'Id':'first', 'Score':'sum', 'ViewCount':'sum'})
.reset_index()
.reindex(columns=df.columns)
)
print (df1)
Id CreationDate Score ViewCount
0 1 2011 109 16125
1 3 2012 36 1015
2 4 2018 33 7064
关于python - Pandas、groupby 和计数其他列中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55241405/