一行Pandas代碼制作數(shù)據(jù)分析透視表,太牛了!

導(dǎo)入模塊和讀取數(shù)據(jù)
那我們第一步仍然是導(dǎo)入模塊并且來(lái)讀取數(shù)據(jù),數(shù)據(jù)集是北美咖啡的銷售數(shù)據(jù),包括了咖啡的品種、銷售的地區(qū)、銷售的利潤(rùn)和成本、銷量以及日期等等。
import pandas as pd
def load_data():
return pd.read_csv('coffee_sales.csv', parse_dates=['order_date'])
那小編這里將讀取數(shù)據(jù)封裝成了一個(gè)自定義的函數(shù),讀者也可以根據(jù)自己的習(xí)慣來(lái)進(jìn)行數(shù)據(jù)的讀取。
df = load_data()
df.head()
output

通過(guò)調(diào)用info()函數(shù)先來(lái)對(duì)數(shù)據(jù)集有一個(gè)大致的了解。
df.info()
output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4248 entries, 0 to 4247
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 order_date 4248 non-null datetime64[ns]
1 market 4248 non-null object
2 region 4248 non-null object
3 product_category 4248 non-null object
4 product 4248 non-null object
5 cost 4248 non-null int64
6 inventory 4248 non-null int64
7 net_profit 4248 non-null int64
8 sales 4248 non-null int64
dtypes: datetime64[ns](1), int64(4), object(4)
memory usage: 298.8+ KB
初體驗(yàn)
在pivot_table函數(shù)當(dāng)中最重要的四個(gè)參數(shù)分別是index、values、columns以及aggfunc,其中每個(gè)數(shù)據(jù)透視表都必須要有一個(gè)index,例如我們想看每個(gè)地區(qū)咖啡的銷售數(shù)據(jù),就將“region”設(shè)置為index。
df.pivot_table(index='region')
output

當(dāng)然我們還可以更加細(xì)致一點(diǎn),查看每個(gè)地區(qū)中不同咖啡種類的銷售數(shù)據(jù),因此在索引中我們引用“region”以及“product_category”兩個(gè),代碼如下:
df.pivot_table(index=['region', 'product_category'])
output

進(jìn)階的操作
上面的案例當(dāng)中,我們以地區(qū)“region”為索引看到了各項(xiàng)銷售指標(biāo),當(dāng)中有成本、庫(kù)存、凈利潤(rùn)以及銷量這個(gè)4個(gè)指標(biāo)的數(shù)據(jù),那要是我們想要單獨(dú)拎出某一個(gè)指標(biāo)來(lái)看的話,代碼如下所示:
df.pivot_table(index=['region'], values=['sales'])
output

這也就是我們上面提到的values,在上面的案例當(dāng)中我們就單獨(dú)拎出了“銷量”這一指標(biāo),又或者我們想要看一下凈利潤(rùn),代碼如下:
df.pivot_table(index=['region'], values=['net_profit'])
output

另外我們也提到了aggfunc,可以設(shè)置我們對(duì)數(shù)據(jù)聚合時(shí)進(jìn)行的函數(shù)操作,通常情況下,默認(rèn)的都是求平均數(shù),這里我們也可以指定例如去計(jì)算總數(shù)。
df.pivot_table(index=['region'], values=['sales'], aggfunc='sum')
output

或者我們也可以這么來(lái)寫(xiě)。
df.pivot_table(index=['region'], values=['sales'], aggfunc={ 'sales': 'sum' })
當(dāng)然我們要是覺(jué)得只有一個(gè)聚合函數(shù)可能還不夠,我們可以多來(lái)添加幾個(gè)。
df.pivot_table(index=['region'], values=['sales'], aggfunc=['sum', 'count'])
output

剩下最后的一個(gè)關(guān)鍵參數(shù)columns類似于之前提到的index用來(lái)設(shè)置列層次的字段,當(dāng)然它并不是一個(gè)必要的參數(shù),例如:
df.pivot_table(index=['region'], values=['sales'], aggfunc='sum', columns=['product_category'])
output

在“列”方向上表示每種咖啡在每個(gè)地區(qū)的銷量總和,要是我們不調(diào)用columns參數(shù),而是統(tǒng)一作為index索引的話,代碼如下:
df.pivot_table(index=['region', 'product_category'], values=['sales'], aggfunc='sum')
output

同時(shí)我們看到當(dāng)中存在著一些缺失值,我們可以選擇將這些缺失值替換掉。
df.pivot_table(index=['region', 'product_category'], values=['sales'], aggfunc='sum')
output

熟能生巧
我們?cè)賮?lái)做幾組練習(xí),我們除了想要知道銷量之外還想知道各個(gè)品種的咖啡在每個(gè)地區(qū)的成本如何,我們?cè)趘alues當(dāng)中添加“cost”的字段,代碼如下:
df.pivot_table(index=['region'], values=['sales', 'cost'], aggfunc='sum', columns=['product_category'], fill_value=0)
output

同時(shí)我們還能夠計(jì)算出總量,通過(guò)調(diào)用margin這個(gè)參數(shù)。
df.pivot_table(index=['region', 'product_category'], values=['sales', 'cost'], aggfunc='sum', fill_value=0, margins=True)
output

最后的最后,我們調(diào)用pivot_table函數(shù)來(lái)制作一個(gè)2010年度咖啡銷售的銷量年報(bào),代碼如下:
month_gp = pd.Grouper(key='order_date',freq='M')
cond = df["order_date"].dt.year == 2010
df[cond].pivot_table(index=['region','product_category'],
columns=[month_gp],
values=['sales'],
aggfunc=['sum'])
output


































