99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀一行Pandas代碼制作數(shù)據(jù)分析透視表,太牛了
一行Pandas代碼制作數(shù)據(jù)分析透視表,太牛了
2022-06-07
收藏

作者:俊欣

來源:關(guān)于數(shù)據(jù)分析與可視化

相信大家都用在Excel當(dāng)中使用過數(shù)據(jù)透視表(一種可以對(duì)數(shù)據(jù)動(dòng)態(tài)排布并且分類匯總的表格格式),也體驗(yàn)過它的強(qiáng)大功能,在Pandas模塊當(dāng)中被稱作是pivot_table,今天小編就和大家來詳細(xì)聊聊該函數(shù)的主要用途。

導(dǎo)入模塊和讀取數(shù)據(jù)

那我們第一步仍然是導(dǎo)入模塊并且來讀取數(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í)慣來進(jìn)行數(shù)據(jù)的讀取

df = load_data()
df.head()

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

通過調(diào)用info()函數(shù)先來對(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

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

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

df.pivot_table(index=['region', 'product_category'])

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

進(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)來看的話,代碼如下所示

df.pivot_table(index=['region'], values=['sales'])

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

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

df.pivot_table(index=['region'], values=['net_profit'])

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

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

df.pivot_table(index=['region'], values=['sales'], aggfunc='sum')

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

或者我們也可以這么來寫

df.pivot_table(index=['region'], values=['sales'], aggfunc={ 'sales': 'sum' })

當(dāng)然我們要是覺得只有一個(gè)聚合函數(shù)可能還不夠,我們可以多來添加幾個(gè)

df.pivot_table(index=['region'], values=['sales'], aggfunc=['sum', 'count'])

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

剩下最后的一個(gè)關(guān)鍵參數(shù)columns類似于之前提到的index用來設(shè)置列層次的字段,當(dāng)然它并不是一個(gè)必要的參數(shù),例如

df.pivot_table(index=['region'], values=['sales'], aggfunc='sum', columns=['product_category'])

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

在“列”方向上表示每種咖啡在每個(gè)地區(qū)的銷量總和,要是我們不調(diào)用columns參數(shù),而是統(tǒng)一作為index索引的話,代碼如下

df.pivot_table(index=['region', 'product_category'], values=['sales'], aggfunc='sum')

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

同時(shí)我們看到當(dāng)中存在著一些缺失值,我們可以選擇將這些缺失值替換掉

df.pivot_table(index=['region', 'product_category'], values=['sales'], aggfunc='sum')

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

熟能生巧

我們?cè)賮碜鰩捉M練習(xí),我們除了想要知道銷量之外還想知道各個(gè)品種的咖啡在每個(gè)地區(qū)的成本如何,我們?cè)?/span>values當(dāng)中添加“cost”的字段,代碼如下

df.pivot_table(index=['region'], values=['sales', 'cost'], aggfunc='sum', columns=['product_category'], fill_value=0)

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

同時(shí)我們還能夠計(jì)算出總量,通過調(diào)用margin這個(gè)參數(shù)

df.pivot_table(index=['region', 'product_category'], values=['sales', 'cost'], aggfunc='sum', fill_value=0, margins=True)

output

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

最后的最后,我們調(diào)用pivot_table函數(shù)來制作一個(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

一行Pandas代碼制作數(shù)據(jù)分析<a href='/map/toushibiao/' style='color:#000;font-size:inherit;'>透視表</a>,太牛了

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }