pandas groupby 分組結(jié)果保存成DataFrame
今天做項目需要將groupby分組結(jié)果保存 成DataFrame,現(xiàn)在就講解一下具體實現(xiàn)方式:
原始數(shù)據(jù)及代碼:
import pandasas pd
from pyechartsimport Line
df= pd.DataFrame({'name': ['張三','李四','王五','張三','王五','張三','趙六','張三','趙六'],
????????????????????????????????????? 'sex': ['男','女','男','男','男','男','女','女','女'],
?????????????????????????????????????? 'num1': [2.9,9.0,8.5,5.6,5.6,5.2,1.2,4.5,3.2],
??????????????????????????????????????? 'num2': [5.2,2.5,6.3,5.6,4.5,5.6,1.2,8.5,1.2]
??????????????????????????????????? })
# 根據(jù)其中兩列分組,并求均值
df_expenditure_mean= df.groupby(['sex','name'])['num1'].agg({'means':'mean'})
print(df_expenditure_mean)
groupby分組結(jié)果保存 成DataFrame方法:
import pandasas pd
from pyechartsimport Line
df= pd.DataFrame({'name': ['張三','李四','王五','張三','王五','張三','趙六','張三','趙六'],
????????????????????????????????????? 'sex': ['男','女','男','男','男','男','女','女','女'],
?????????????????????????????????????? 'num1': [2.9,9.0,8.5,5.6,5.6,5.2,1.2,4.5,3.2],
??????????????????????????????????????? 'num2': [5.2,2.5,6.3,5.6,4.5,5.6,1.2,8.5,1.2]
??????????????????????????????????? })
# 根據(jù)其中兩列分組雄可,并求均值
df_expenditure_mean= df.groupby(['sex','name'])['num1'].agg({'means':'mean'})
#轉(zhuǎn)化成dataframe格式
df_expenditure_mean = pd.DataFrame(df_expenditure_mean)
#修改字段名稱
df_expenditure_mean.rename(columns={'sex':'性別','name':'姓名','means':'均值'},inplace=True)
print(df_expenditure_mean)
好啦曲伊,groupby分組結(jié)果保存 成DataFrame已經(jīng)成功堕花,謝謝泛鸟。