Pandas数据透视表之pivot_table

版权声明: https://blog.csdn.net/hhq2lcl/article/details/84679060

数据源:https://www.kaggle.com/mjbahmani/machine-learning-workflow-for-house-prices/data

1、pivot_table定义

df.pivot_table(values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')
参数解析:
values:数据透视表中的;                                                                                                                                                                 index:数据表中的行(索引);
columns:数据表中的列;
aggfunc:统计函数(np.sum,len,min,max)
fill_value:默认NA作为空值 (也可以设置:fill_value=0)
margins:汇总(默认是False);
aggfunc:统计函数(np.sum,len)
fill_value:默认NA作为空值 (也可以设置:fill_value=0)

2、数据加载

3、pivot_table由简入繁:

若是aggfunc不定义的话,默认结果为-数值变量的——平均值。

1)index="SaleCondition"

2)缺columns

3、index、columns、values、总计齐全

pd.pivot_table(df,index=["Ship_Mode",'Category'],values=['Profit','Sales'],columns='Sales_area',margins=True,aggfunc=np.sum,margins_name='总计')

4、多个同级索引

sales=pd.pivot_table(df,index=['Sales_area',"Segment"],columns="Ship_Mode",values=["Quantity","Sales"],aggfunc=len,margins=True)
area=pd.pivot_table(df,index=['Segment','Category'],columns="Ship_Mode",values=["Quantity","Sales"],aggfunc=len,margins=True)
pd.concat([sales,area],axis=0)

猜你喜欢

转载自blog.csdn.net/hhq2lcl/article/details/84679060
今日推荐