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

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單(CDA內(nèi)容分享)
22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單(CDA內(nèi)容分享)
2022-01-12
收藏

作者:俊欣

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

今天小編打算來(lái)講一講數(shù)據(jù)分析方面的內(nèi)容,整理和總結(jié)一下Pandas數(shù)據(jù)預(yù)處理和數(shù)據(jù)分析方面的硬核干貨,我們大致會(huì)說(shuō)

  • Pandas計(jì)算交叉列表
  • Pandas將字符串與數(shù)值轉(zhuǎn)化成時(shí)間類型
  • Pandas將字符串轉(zhuǎn)化成數(shù)值類型

Pandas當(dāng)中的交叉列表

首先我們來(lái)講一下Pandas模塊當(dāng)中的crosstab()函數(shù),它的作用主要是進(jìn)行分組之后的信息統(tǒng)計(jì),里面會(huì)用到聚合函數(shù),默認(rèn)的是統(tǒng)計(jì)行列組合出現(xiàn)的次數(shù),參數(shù)如下

pandas.crosstab(index, columns, values=None,
                rownames=None,
                colnames=None,
                aggfunc=None,
                margins=False,
                margins_name='All',
                dropna=True,
                normalize=False)

下面小編來(lái)解釋一下里面幾個(gè)常用的函數(shù)

  • index: 指定了要分組的類目,作為行
  • columns: 指定了要分組的類目,作為列
  • rownames/colnames: 行/列的名稱
  • aggfunc: 指定聚合函數(shù)
  • values: 最終在聚合函數(shù)之下,行與列一同計(jì)算出來(lái)的值
  • normalize: 標(biāo)準(zhǔn)化統(tǒng)計(jì)各行各列的百分比

我們通過(guò)幾個(gè)例子來(lái)進(jìn)一步理解corss_tab()函數(shù)的作用,我們先導(dǎo)入要用到的模塊并且讀取數(shù)據(jù)集

import pandas as pd df = pd.read_excel( io="supermarkt_sales.xlsx", engine="openpyxl", sheet_name="Sales", skiprows=3, usecols="B:R", nrows=1000, ) 

output

我們先簡(jiǎn)單來(lái)看幾個(gè)corsstab()函數(shù)的例子,代碼如下

pd.crosstab(df['城市'], df['顧客類型'])

output

顧客類型 會(huì)員 普通 省份 上海 124 115 北京 116 127 四川 26 35 安徽 28 12 廣東 30 36 ....... 

這里我們將省份指定為行索引,將會(huì)員類型指定為列,其中顧客類型有“會(huì)員”、“普通”兩種,舉例來(lái)說(shuō),四川省的會(huì)員顧客有26名,普通顧客有35名。

當(dāng)然我們這里只是指定了一個(gè)列,也可以指定多個(gè),代碼如下

pd.crosstab(df['省份'], [df['顧客類型'], df["性別"]])

output

顧客類型 會(huì)員 普通 性別 女性 男性 女性 男性 省份 上海 67 57 53 62 北京 53 63 59 68 四川 17 9 16 19 安徽 17 11 9 3 廣東 18 12 15 21 ..... 

這里我們將顧客類型進(jìn)行了細(xì)分,有女性會(huì)員、男性會(huì)員等等,那么同理,對(duì)于行索引我們也可以指定多個(gè),這里也就不過(guò)多進(jìn)行演示。

有時(shí)候我們想要改變行索引的名稱或者是列方向的名稱,我們則可以這么做

pd.crosstab(df['省份'], df['顧客類型'],
            colnames = ['顧客的類型'],
            rownames = ['各省份名稱'])

output

顧客的類型 會(huì)員 普通 各省份名稱 上海 124 115 北京 116 127 四川 26 35 安徽 28 12 廣東 30 36 

要是我們想在行方向以及列方向上加一個(gè)匯總的列,就需要用到crosstab()方法當(dāng)中的margin參數(shù),如下

pd.crosstab(df['省份'], df['顧客類型'], margins = True)

output

顧客類型 會(huì)員 普通 All 省份 上海 124 115 239 北京 116 127 243 ..... 江蘇 18 15 33 浙江 119 111 230 黑龍江 14 17 31 All 501 499 1000 

你也可以給匯總的那一列重命名,用到的是margins_name參數(shù),如下

pd.crosstab(df['省份'], df['顧客類型'],
            margins = True, margins_name="匯總")

output

顧客類型 會(huì)員 普通 匯總 省份 上海 124 115 239 北京 116 127 243 ..... 江蘇 18 15 33 浙江 119 111 230 黑龍江 14 17 31 匯總 501 499 1000 

而如果我們需要的數(shù)值是百分比的形式,那么就需要用到normalize參數(shù),如下

pd.crosstab(df['省份'], df['顧客類型'],
            normalize=True)

output

顧客類型     會(huì)員     普通
省份                
上海    0.124 0.115 北京    0.116 0.127 四川    0.026 0.035 安徽    0.028 0.012 廣東    0.030 0.036 .......

要是我們更加傾向于是百分比,并且保留兩位小數(shù),則可以這么來(lái)做

pd.crosstab(df['省份'], df['顧客類型'],
            normalize=True).style.format('{:.2%}')

output

顧客類型 會(huì)員 普通 省份 上海 12.4% 11.5% 北京 11.6% 12.7% 四川 26% 35% 安徽 28% 12% 廣東 30% 36% ....... 

下面我們指定聚合函數(shù),并且作用在我們指定的列上面,用到的參數(shù)是aggfunc參數(shù)以及values參數(shù),代碼如下

pd.crosstab(df['省份'], df['顧客類型'],
            values = df["總收入"],
            aggfunc = "mean")

output

顧客類型         會(huì)員         普通
省份                        
上海    15.648738 15.253248 北京    14.771259 14.354390 四川    20.456135 14.019029 安徽    10.175893 11.559917 廣東    14.757083 18.331903 .......

如上所示,我們所要計(jì)算的是地處“上?!辈⑶沂恰皶?huì)員”顧客的總收入的平均值,除了平均值之外,還有其他的聚合函數(shù),如np.sum加總或者是np.median求取平均值。

我們還可以指定保留若干位的小數(shù),使用round()函數(shù)

df_1 = pd.crosstab(df['省份'], df['顧客類型'],
                   values=df["總收入"],
                   aggfunc="mean").round(2)

output

顧客類型     會(huì)員     普通
省份                
上海    15.65 15.25 北京    14.77 14.35 四川    20.46 14.02 安徽    10.18 11.56 廣東    14.76 18.33 .......

時(shí)間類型數(shù)據(jù)的轉(zhuǎn)化

對(duì)于很多數(shù)據(jù)分析師而言,在進(jìn)行數(shù)據(jù)預(yù)處理的時(shí)候,需要將不同類型的數(shù)據(jù)轉(zhuǎn)換成時(shí)間格式的數(shù)據(jù),我們來(lái)看一下具體是怎么來(lái)進(jìn)行

首先是將整形的時(shí)間戳數(shù)據(jù)轉(zhuǎn)換成時(shí)間類型,看下面的例子

df = pd.DataFrame({'date': [1470195805, 1480195805, 1490195805], 'value': [2, 3, 4]}) pd.to_datetime(df['date'], unit='s') 

output

0 2016-08-03 03:43:25 1 2016-11-26 21:30:05 2 2017-03-22 15:16:45 Name: date, dtype: datetime64[ns] 

上面的例子是精確到秒,我們也可以精確到天,代碼如下

df = pd.DataFrame({'date': [1470, 1480, 1490], 'value': [2, 3, 4]}) pd.to_datetime(df['date'], unit='D') 

output

0 1974-01-10 1 1974-01-20 2 1974-01-30 Name: date, dtype: datetime64[ns] 

下面則是將字符串轉(zhuǎn)換成時(shí)間類型的數(shù)據(jù),調(diào)用的也是pd.to_datetime()方法

pd.to_datetime('2022/01/20', format='%Y/%m/%d')

output

Timestamp('2022-01-20 00:00:00')

亦或是

pd.to_datetime('2022/01/12 11:20:10',
               format='%Y/%m/%d %H:%M:%S')

output

Timestamp('2022-01-12 11:20:10')

這里著重介紹一下Python當(dāng)中的時(shí)間日期格式化符號(hào)

  • %y 兩位數(shù)的年份表示(00-99)
  • %Y 四位數(shù)的年份表示(000-9999)
  • %m 表示的是月份(01-12)
  • %d 表示的是一個(gè)月當(dāng)中的一天(0-31)
  • %H 表示的是24小時(shí)制的小時(shí)數(shù)
  • %I 表示的是12小時(shí)制的小時(shí)數(shù)
  • %M 表示的是分鐘數(shù) (00-59)
  • %S 表示的是秒數(shù)(00-59)
  • %w 表示的是星期數(shù),一周當(dāng)中的第幾天,從星期天開(kāi)始算
  • %W 表示的是一年中的星期數(shù)

當(dāng)然我們進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換遇到錯(cuò)誤的時(shí)候,pd.to_datetime()方法當(dāng)中的errors參數(shù)就可以派上用場(chǎng),

df = pd.DataFrame({'date': ['3/10/2000', 'a/11/2000', '3/12/2000'], 'value': [2, 3, 4]}) # 會(huì)報(bào)解析錯(cuò)誤 df['date'] = pd.to_datetime(df['date'])

output

22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單

我們來(lái)看一下errors參數(shù)的作用,代碼如下

df['date'] = pd.to_datetime(df['date'], errors='ignore')
df

output

date value 0 3/10/2000 2 1 a/11/2000 3 2 3/12/2000 4 

或者將不準(zhǔn)確的值轉(zhuǎn)換成NaT,代碼如下

df['date'] = pd.to_datetime(df['date'], errors='coerce')
df

output

date value 0 2000-03-10 2 1 NaT 3 2 2000-03-12 4 

數(shù)值類型的轉(zhuǎn)換

接下來(lái)我們來(lái)看一下其他數(shù)據(jù)類型往數(shù)值類型轉(zhuǎn)換所需要經(jīng)過(guò)的步驟,首先我們先創(chuàng)建一個(gè)DataFrame數(shù)據(jù)集,如下

df = pd.DataFrame({ 'string_col': ['1','2','3','4'], 'int_col': [1,2,3,4], 'float_col': [1.1,1.2,1.3,4.7], 'mix_col': ['a', 2, 3, 4], 'missing_col': [1.0, 2, 3, np.nan], 'money_col': ['£1,000.00','£2,400.00','£2,400.00','£2,400.00'], 'boolean_col': [True, False, True, True], 'custom': ['Y', 'Y', 'N', 'N']
  })

output

22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單

我們先來(lái)查看一下每一列的數(shù)據(jù)類型

df.dtypes 

output

string_col object int_col int64 float_col float64 mix_col object missing_col float64 money_col object boolean_col bool custom object dtype: object 

可以看到有各種類型的數(shù)據(jù),包括了布爾值、字符串等等,或者我們可以調(diào)用df.info()方法來(lái)調(diào)用,如下

df.info()

output

<class 'pandas.core.frame.DataFrame'> RangeIndex: 4 entries, 0 to 3 Data columns (total 8 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  ----- 0 string_col 4 non-null object 1 int_col 4 non-null int64 2 float_col 4 non-null float64 3 mix_col 4 non-null object 4 missing_col 3 non-null float64 5 money_col 4 non-null object 6 boolean_col 4 non-null bool 7 custom 4 non-null object dtypes: bool(1), float64(2), int64(1), object(4)
memory usage: 356.0+ bytes

我們先來(lái)看一下從字符串到整型數(shù)據(jù)的轉(zhuǎn)換,代碼如下

df['string_col'] = df['string_col'].astype('int')
df.dtypes

output

string_col int32 int_col int64 float_col float64 mix_col object missing_col float64 money_col object boolean_col bool custom object dtype: object 

看到數(shù)據(jù)是被轉(zhuǎn)換成了int32類型,當(dāng)然我們指定例如astype('int16')astype('int8')或者是astype('int64'),當(dāng)我們碰到量級(jí)很大的數(shù)據(jù)集時(shí),會(huì)特別的有幫助。

那么類似的,我們想要轉(zhuǎn)換成浮點(diǎn)類型的數(shù)據(jù),就可以這么來(lái)做

df['string_col'] = df['string_col'].astype('float')
df.dtypes

output

string_col float64 int_col int64 float_col float64 mix_col object missing_col float64 money_col object boolean_col bool custom object dtype: object 

同理我們也可以指定轉(zhuǎn)換成astype('float16')、astype('float32')或者是astype('float128')

而如果數(shù)據(jù)類型的混合的,既有整型又有字符串的,正常來(lái)操作就會(huì)報(bào)錯(cuò),如下

df['mix_col'] = df['mix_col'].astype('int')

output

22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單

當(dāng)中有一個(gè)字符串的數(shù)據(jù)"a",這個(gè)時(shí)候我們可以調(diào)用pd.to_numeric()方法以及里面的errors參數(shù),代碼如下

df['mix_col'] = pd.to_numeric(df['mix_col'], errors='coerce')
df.head()

output

22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單

我們來(lái)看一下各列的數(shù)據(jù)類型

df.dtypes 

output

string_col float64 int_col int64 float_col float64 mix_col float64 missing_col float64 money_col object boolean_col bool custom object dtype: object 

"mix_col"這一列的數(shù)據(jù)類型被轉(zhuǎn)換成了float64類型,要是我們想指定轉(zhuǎn)換成我們想要的類型,例如

df['mix_col'] = pd.to_numeric(df['mix_col'], errors='coerce').astype('Int64')
df['mix_col'].dtypes

output

Int64Dtype()

而對(duì)于"money_col"這一列,在字符串面前有一個(gè)貨幣符號(hào),并且還有一系列的標(biāo)簽符號(hào),我們先調(diào)用replace()方法將這些符號(hào)給替換掉,然后再進(jìn)行數(shù)據(jù)類型的轉(zhuǎn)換

df['money_replace'] = df['money_col'].str.replace('£', '').str.replace(',','')
df['money_replace'] = pd.to_numeric(df['money_replace'])
df['money_replace']

output

0 1000.0 1 2400.0 2 2400.0 3 2400.0 Name: money_replace, dtype: float64 

要是你熟悉正則表達(dá)式的話,也可以通過(guò)正則表達(dá)式的方式來(lái)操作,通過(guò)調(diào)用regex=True的參數(shù),代碼如下

df['money_regex'] = df['money_col'].str.replace('[£,]', '', regex=True)
df['money_regex'] = pd.to_numeric(df['money_regex'])
df['money_regex']

另外我們也可以通過(guò)astype()方法,對(duì)多個(gè)列一步到位進(jìn)行數(shù)據(jù)類型的轉(zhuǎn)換,代碼如下

df = df.astype({ 'string_col': 'float16', 'int_col': 'float16' })

或者在第一步數(shù)據(jù)讀取的時(shí)候就率先確定好數(shù)據(jù)類型,代碼如下

df = pd.read_csv( 'dataset.csv', 
    dtype={ 'string_col': 'float16', 'int_col': 'float16' }
)
22個(gè)案例詳解Pandas數(shù)據(jù)分析/預(yù)處理時(shí)的實(shí)用技巧,超簡(jiǎn)單

數(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ù)說(shuō)明請(qǐng)參見(jiàn):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); }