【问题标题】:Resample pandas dataframe based on two columns基于两列重新采样熊猫数据框
【发布时间】:2020-11-18 21:14:29
【问题描述】:

我得到了一个包含两列的 pandas 数据框。日期和评级编号,如下所示:

       Date            Rating
    0  2020-07-28      9
    1  2020-07-28      10
    2  2020-07-27      8
    3  2020-07-26      10
    4  2020-07-26      9
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100 entries, 0 to 99

我想以每天的时间间隔重新采样 DataFrame 并计算每天的评分量并获得每天的平均评分。所以新的数据框应该是这样的:

   Date            Amount of Ratings      Average rating
0  2020-07-28      2                      9.5
1  2020-07-27      1                      8
2  2020-07-26      2                      9.5

我该怎么做?

我将索引更改为 Datetimeindex 并使用 count() 计算行数,但它计算所有列,我想将 Rating 列重新采样为每天的平均评级。

这是我尝试过的:

df = df.set_index(pd.to_datetime(df['Date']))
df_resampled = df.resample('D').count()

Output:
               Date    Rating
Date                    
2020-07-21     17      17
2020-07-22     14      14
2020-07-23     16      16
2020-07-24     14      14
2020-07-25      9       9

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用df.agg() 聚合多个列上的不同操作

    df_resampled = df.resample('D').agg({'Date': 'count', 'Value': 'mean'}))
    df_resampled = df_resampled.rename(columns = {'Date' : 'Amount of Ratings' , 'Value' : 'Average rating'})
    
    Output:
                   Amount of Ratings     Average rating
    Date                   
    2020-07-26     2                     9.5
    2020-07-27     1                     8.0
    2020-07-28     2                     9.5
    

    【讨论】:

      【解决方案2】:

      你可以使用 Group by Agg 来解决这个问题:

      df2= df.groupby(['Date'], as_index=False).agg(['mean', 'count'])
      df2.columns = ['Average rating',  'Amount of Ratings']
      df2 = df2.reset_index()
      df2
      

      输出:

             Date      Average rating   Amount of Ratings
      0   2020-07-26       9.5               2
      1   2020-07-27       8.0               1
      2   2020-07-28       9.5               2
      

      在here查看更多信息

      【讨论】:

        猜你喜欢
        • 2017-05-28
        • 1970-01-01
        • 1970-01-01
        • 2018-12-18
        • 2016-03-19
        • 2020-01-10
        • 2018-03-26
        • 2019-07-04
        • 2018-07-05
        相关资源
        最近更新 更多