簡體   English   中英

基於兩列重采樣 pandas dataframe

[英]Resample pandas dataframe based on two columns

我得到了一個有兩列的 pandas dataframe。 日期和評級編號,如下所示:

       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 重新采樣,計算每天的評分數量並獲得每天的平均評分。 所以新的 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() 計算行數,但它計算所有列,我想在其中將評級列重新采樣為每天平均評級。

這是我試過的:

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

使用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

您可以使用 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

Output:

       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

這里查看更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM