【问题标题】:Pandas, groupby and counting data in others columnsPandas、groupby 和其他列中的计数数据
【发布时间】:2019-08-10 00:06:13
【问题描述】:

我有四列数据,包括:IdCreationDateScoreViewCount

CreationDate 具有下一个格式,例如:2011-11-30 19:41:14.960。 我需要对CreationDate 的年份进行分组,计算它们,将ScoreViewCount 相加,并添加到其他列中。

我想与 pandas 库一起使用。

谢谢!

更改之前 - 示例:

     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                            

【问题讨论】:

    标签: python pandas numpy data-science data-analysis


    【解决方案1】:

    您可以通过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
    

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 2021-05-24
      • 2020-10-04
      • 2022-07-19
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多