[英]Pandas groupby mean - into a dataframe?
假設我的數據如下所示:
date,name,id,dept,sale1,sale2,sale3,total_sale
1/1/17,John,50,Sales,50.0,60.0,70.0,180.0
1/1/17,Mike,21,Engg,43.0,55.0,2.0,100.0
1/1/17,Jane,99,Tech,90.0,80.0,70.0,240.0
1/2/17,John,50,Sales,60.0,70.0,80.0,210.0
1/2/17,Mike,21,Engg,53.0,65.0,12.0,130.0
1/2/17,Jane,99,Tech,100.0,90.0,80.0,270.0
1/3/17,John,50,Sales,40.0,50.0,60.0,150.0
1/3/17,Mike,21,Engg,53.0,55.0,12.0,120.0
1/3/17,Jane,99,Tech,80.0,70.0,60.0,210.0
我想要一個新列average
,它是每個name,id,dept
元組的total_sale
的平均值
我試過了
df.groupby(['name', 'id', 'dept'])['total_sale'].mean()
這確實返回了一個具有平均值的系列:
name id dept
Jane 99 Tech 240.000000
John 50 Sales 180.000000
Mike 21 Engg 116.666667
Name: total_sale, dtype: float64
但我將如何引用數據? 該系列是形狀 (3,) 的一維系列。 理想情況下,我希望將其放回具有適當列的 dataframe 中,以便我可以通過name/id/dept
正確引用。
如果您在您擁有的系列上調用.reset_index()
,它將為您提供您想要的數據.reset_index()
索引的每個級別都將轉換為一列):
df.groupby(['name', 'id', 'dept'])['total_sale'].mean().reset_index()
編輯:為了回應 OP 的評論,將此列添加回原始數據框有點棘手。 您的行數與原始數據框中的行數不同,因此您還不能將其分配為新列。 但是,如果您將索引設置為相同, pandas
很聰明,並且會為您正確填寫值。 嘗試這個:
cols = ['date','name','id','dept','sale1','sale2','sale3','total_sale']
data = [
['1/1/17', 'John', 50, 'Sales', 50.0, 60.0, 70.0, 180.0],
['1/1/17', 'Mike', 21, 'Engg', 43.0, 55.0, 2.0, 100.0],
['1/1/17', 'Jane', 99, 'Tech', 90.0, 80.0, 70.0, 240.0],
['1/2/17', 'John', 50, 'Sales', 60.0, 70.0, 80.0, 210.0],
['1/2/17', 'Mike', 21, 'Engg', 53.0, 65.0, 12.0, 130.0],
['1/2/17', 'Jane', 99, 'Tech', 100.0, 90.0, 80.0, 270.0],
['1/3/17', 'John', 50, 'Sales', 40.0, 50.0, 60.0, 150.0],
['1/3/17', 'Mike', 21, 'Engg', 53.0, 55.0, 12.0, 120.0],
['1/3/17', 'Jane', 99, 'Tech', 80.0, 70.0, 60.0, 210.0]
]
df = pd.DataFrame(data, columns=cols)
mean_col = df.groupby(['name', 'id', 'dept'])['total_sale'].mean() # don't reset the index!
df = df.set_index(['name', 'id', 'dept']) # make the same index here
df['mean_col'] = mean_col
df = df.reset_index() # to take the hierarchical index off again
添加到to_frame
df.groupby(['name', 'id', 'dept'])['total_sale'].mean().to_frame()
你很親近。 您只需要在[['total_sale']]
周圍添加一組括號來告訴 python 選擇作為數據框而不是系列:
df.groupby(['name', 'id', 'dept'])[['total_sale']].mean()
如果您想要所有列:
df.groupby(['name', 'id', 'dept'], as_index=False).mean()[['name', 'id', 'dept', 'total_sale']]
答案在兩行代碼中:
第一行創建分層框架。
df_mean = df.groupby(['name', 'id', 'dept'])[['total_sale']].mean()
第二行將其轉換為具有四列的數據框('name', 'id', 'dept', 'total_sale')
df_mean = df_mean.reset_index()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.