簡體   English   中英

使用平均值從 pandas.DataFrame.groupby(['arg1', 'arg2']) 創建新列

[英]Creating new columns from pandas.DataFrame.groupby(['arg1', 'arg2']) with mean values

我在 pandas.DataFrame 中有類似以下的數據:

df = pd.DataFrame({
    'Year' : [2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002],
    'Month' : ['Aug', 'Aug', 'Sep', 'Sep', 'Aug', 'Aug', 'Sep', 'Sep'],
    'Day' : [1, 2, 1, 2, 1, 2, 1, 2],
    'Value' : [1, 2, 3, 4, 5, 6, 7, 8]  })

現在我按“月”和“年”分組,並計算平均值:

print(df.groupby(['Month', 'Year'])['Value'].mean())

output 看起來像:

八月 2001年 1.5
2002年 5.5
九月 2001年 3.5
2002年 7.5

現在我想創建一個新的數據框,如下所示:

八月 九月
2001年 1.5 3.5
2002年 5.5 7.5

pandas 模塊中是否有任何功能可以幫助我解決這個問題? 提前致謝!

您可以使用 pivot_table 這樣做:

table = pd.pivot_table(df, values='Value', index=['Year'],
                columns=['Month'], aggfunc=np.mean)

問候,傑霍娜。

OP離預期的目標不遠了。 因為一個人正在使用pandas.DataFrame.groupbypandas.Series.mean ,所以一個人所要做的就是使用pandas.DataFrame.unstack如下

df_new = df.groupby(['Year', 'Month'])['Value'].mean().unstack()

[Out]:

Month  Aug  Sep
Year           
2001   1.5  3.5
2002   5.5  7.5

在此處輸入圖像描述

暫無
暫無

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

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