1 基本使用方法
pandas.pivot_table(
data,
values=None,
index=None,
columns=None,
aggfunc='mean',
fill_value=None,
margins=False,
dropna=True,
margins_name='All',
observed=False,
sort=True)
2 主要參數(shù)
data | DataFrame |
values | 要進(jìn)行聚合的列 |
index | 在數(shù)據(jù)透視表索引(index)上進(jìn)行分組的鍵 |
columns | 在數(shù)據(jù)透視表列(column)上進(jìn)行分組的鍵 |
agg_func | 聚合方式 |
fill_value | 缺省值的填充方式,默認(rèn)為NAN |
margins | 默認(rèn)為False,設(shè)置為True之后,會(huì)計(jì)算一個(gè)總的value值 |
3 使用方法
3.0 導(dǎo)入數(shù)據(jù)
import pandas as pd
# Visual Python: Data Analysis > File
vp_df = pd.read_csv('https://raw.githubusercontent.com/visualpython/visualpython/main/visualpython/data/sample_csv/tips.csv')
import seaborn as sns
import numpy as np
vp_df.head()
3.1 基本使用
vp_df.pivot_table(index='day',
columns='time',
values='total_bill')
?
?3.2 index
- aggfunc默認(rèn)按平均值聚合,values默認(rèn)只顯示可以按平均值聚合的數(shù)據(jù)
index為一列名字的效果如3.1所示,多列的話,效果如下
vp_df.pivot_table(index=['day','size'],
columns='time',
values='total_bill')
?順序不同,效果也不同
?3.3 values
篩選需要顯示的列
values 中一個(gè)元素的結(jié)果和3.1一樣,如果是多個(gè)元素,那就是一個(gè)value的透視表之后接另一個(gè):
vp_df.pivot_table(index='day',
columns='time',
values=['total_bill','size'])
?3.4 columns
列索引
columns中一個(gè)元素的結(jié)果和3.1一樣,如果是多個(gè)元素,那就是
vp_df.pivot_table(index='day',
columns=['time','size'],
values='total_bill')
3.5 aggfunc
聚合方式,默認(rèn)為求平均
vp_df.pivot_table(index='day',
columns='time',
values='total_bill',
aggfunc=sum)
3.5.1 不同的列不同的聚合方式
vp_df.pivot_table(index='day',
columns='time',
values=['total_bill','size'],
aggfunc={'total_bill':sum,'size':min},
margins=True)
?3.5 fill_value
vp_df.pivot_table(index='day',
columns='time',
values='total_bill',
fill_value='Not a Num')
?3.6 margins
vp_df.pivot_table(index='day',
columns='time',
values='total_bill',
aggfunc=sum,
margins=True)
4 pivot
不同于pivot_table,pivot不會(huì)進(jìn)行聚合操作,換言之,如果index中有重復(fù)值,那么pivot會(huì)報(bào)錯(cuò)
vp_df.pivot_table(index='day',
columns='time',
values='total_bill')
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-584739.html
vp_df.pivot(index='day',
columns='time',
values='total_bill')
#ValueError: Index contains duplicate entries, cannot reshape
vp_df.pivot_table(index='tip',
columns='time',
values='total_bill')
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-584739.html
?
到了這里,關(guān)于pandas 筆記:pivot_table 數(shù)據(jù)透視表的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!