資料分析———pandas基礎(三)

接著之前的文章,在這裡我們來看一些利用pandas處理文字資料,利用索引,loc, iloc,ix,屬性選取資料

一、 處理文字資料

在這裡我們用基本的序列、索引來進行字串操作

先大致瞭解一下我們將要用到的函式。

資料分析———pandas基礎(三)

下面我們就來看一下具體的例子:

1)lower()

將字串中的字元均轉換成小寫字母

import numpy as npimport pandas as pd# 處理文字資料s = pd。Series([‘Tom’, ‘William Rick’, ‘John’, ‘Alber@t’, np。nan, ‘1234’,‘SteveSmith’])print(s)print(s。str。lower()) # 將Series / Index中的字串轉換為小寫字母。“”“輸出:s:0 Tom1 William Rick2 John3 Alber@t4 NaN5 12346 SteveSmithdtype: object

lower:0 tom1 william rick2 john3 alber@t4 NaN5 12346 stevesmithdtype: object”“”

2)upper()

將字串轉換為大寫

print(s。str。upper()) # 將Series / Index中的字串轉換為大寫。“”“輸出:0 TOM1 WILLIAM RICK2 JOHN3 ALBER@T4 NaN5 12346 STEVESMITHdtype: object”“”

3) len()

計算字串的長度

print(s。str。len())“”“輸出:0 3。01 12。02 4。03 7。04 NaN5 4。06 10。0dtype: float64”“”

4) strip()

刪除字串前後的空格

s1 = pd。Series([‘Tom ’, ‘ William Rick ’, ‘John’, ‘Alber@t ’])print(s1)print(“after striping”)print(s1。str。strip()) #從兩側刪除Series / index中每個字串的空格(包括換行符)“”“輸出:0 Tom 1 William Rick 2 John3 Alber@t dtype: object

after striping0 Tom1 William Rick2 John3 Alber@tdtype: object”“”

5) cat()

使用特點符號將字串連線

s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])s。str。cat(sep=‘_’) # 使用給定的分隔符連線序列/索引元素。“”“輸出:‘Tom _William Rick_John_Alber@t’”“”

6)get_dummies()

轉換成one_hot編碼,也即0,1編碼,在之前的文章中有介紹過numpy下的one_hot編碼。(資料分析 ——— numpy基礎(三))

s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s。str。get_dummies()) # 用One-Hot Encoded值返回DataFrame“”“輸出: Alber@t John Tom William Rick0 0 0 1 01 0 0 0 12 0 1 0 03 1 0 0 0”“”

7) contains()

檢視字串包含在元素中,則返回每個元素的布林值True,否則返回False。

# 檢視是否含有空格print(s。str。contains(‘ ’)) # 如果字串包含在元素中,則返回每個元素的布林值True,否則返回False。“”“輸出:0 True1 True2 False3 Falsedtype: bool”“”

8) replace()

字串替換

# 將a替換成b s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s,‘\n’)print(“after replacing @ with %:”)print(s。str。replace(‘@’, ‘$’),‘\n’)print(s。str。replace(‘m’, ‘$’))“”“輸出:0 Tom 1 William Rick2 John3 Alber@tdtype: object

after replacing @ with %:0 Tom 1 William Rick2 John3 Alber$tdtype: object

0 To$ 1 Willia$ Rick2 John3 Alber@tdtype: object”“”

9) repeat()

指定元素的重複次數

# 指定每個元素重複的次數s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s。str。repeat(2))“”“輸出:0 Tom Tom 1 William RickWilliam Rick2 JohnJohn3 Alber@tAlber@tdtype: object”“”

10) count()

每個元素中字元出現次數

# 返回每個元素中字元出現次數。s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(“the number of ‘o’s in each string:”)print(s。str。count(‘o’)) # o在字串中出現 的次數“”“輸出:the number of ‘o’s in each string:0 11 02 13 0dtype: int64”“”

11) startswith()

字串是否由某個字元開始的,是則返回true

# Series / Index中的元素是否以某個字元開始,是則返回trues = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(“string that start with ‘T’:”)print(s。str。startswith(‘T’)) # 看結尾是否是以T開始“”“輸出:string that start with ‘T’:0 True1 False2 False3 Falsedtype: bool”“”

12) endswith()

Series / Index中的元素是否以某個字元結束,是則返回true。

# Series / Index中的元素是否以某個字元結束,是則返回true。s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(“string that end with ‘t’:”)print(s。str。endswith(‘t’))“”“輸出:string that end with ‘t’:0 False1 False2 False3 Truedtype: bool”“”

13)find()

回字符串出現的位置

# 返回字串出現的位置s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s。str。find(‘o’))“”“輸出:

0 11 -12 13 -1dtype: int64”“”

14)findall()

所有字串出現的列表

# 返回所有出現的列表s = pd。Series([‘Tom ’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s。str。findall(‘o’))“”“輸出:0 [o]1 []2 [o]3 []dtype: object”“”

15) swapcase()

檢查Series / Index中每個字串中的所有字元是否小寫,返回布林值

# 檢查Series / Index中每個字串中的所有字元是否小寫,返回布林值s = pd。Series([‘tom’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s。str。islower())“”“輸出:0 True1 False2 False3 Falsedtype: bool”“”

16)isupper()

檢查Series / Index中每個字串中的所有字元是否大寫,返回布林值

# 檢查Series / Index中每個字串中的所有字元是否大寫,返回布林值s = pd。Series([‘Tom’, ‘William Rick’, ‘JOHN’, ‘Alber@t’])print(s。str。isupper())“”“輸出:0 False1 False2 True3 Falsedtype: bool”“”

17)isnumeric()

檢查Series / Index中每個字串中的所有字元是否為數字,返回布林值

# 檢查Series / Index中每個字串中的所有字元是否為數字,返回布林值s = pd。Series([‘1’, ‘William Rick’, ‘John’, ‘Alber@t’])print(s。str。isnumeric())“”“輸出:0 True1 False2 False3 Falsedtype: bool”“”

二、pandas索引,選擇資料

1) loc[]函式

:透過索引‘’index‘’中的具體值來去行資料。中括號裡面是先行後列,以逗號分割,行和列分別是行標籤和列標籤。

# locimport pandas as pdimport numpy as np# pandas 索引# loc採用,為分隔符, 分隔兩個單列df = pd。DataFrame(np。random。randn(8, 4),index = [‘a’,‘b’,‘c’,‘d’,‘e’,‘f’,‘g’,‘h’], columns = [‘A’, ‘B’, ‘C’, ‘D’])print(df)print(df。loc[:,[‘A’,‘C’]]) # 行a~h, 列:A,C兩列print(df。loc[[‘a’,‘b’,‘f’,‘h’],[‘A’,‘D’]]) # 行:a, b,f, h; 列:A, Cprint(df。loc[‘a’:‘h’]) # 行:a~h, 列:所有列“”“輸出:df A B C Da 0。606264 1。841561 -0。225627 0。985734b 1。018913 1。848211 -0。061858 -0。865333c -0。597659 0。136788 1。339162 -1。402188d 0。060156 -0。739114 -0。922197 1。004415e -1。254742 0。164954 -0。025894 0。097442f -0。257760 0。863664 1。237688 1。599834g -0。843632 0。202047 -0。175664 -0。525140h -2。419964 0。264638 0。149577 -0。319869

print(df。loc[:,[‘A’,‘C’]]) # 行a~h, 列:A,C兩列 A Ca 0。606264 -0。225627b 1。018913 -0。061858c -0。597659 1。339162d 0。060156 -0。922197e -1。254742 -0。025894f -0。257760 1。237688g -0。843632 -0。175664h -2。419964 0。149577

print(df。loc[[‘a’,‘b’,‘f’,‘h’],[‘A’,‘D’]]) # 行:a, b,f, h; 列:A, C A Da 0。606264 0。985734b 1。018913 -0。865333f -0。257760 1。599834h -2。419964 -0。319869

print(df。loc[‘a’:‘h’]) # 行:a~h, 列:所有列 A B C Da 0。606264 1。841561 -0。225627 0。985734b 1。018913 1。848211 -0。061858 -0。865333c -0。597659 0。136788 1。339162 -1。402188d 0。060156 -0。739114 -0。922197 1。004415e -1。254742 0。164954 -0。025894 0。097442f -0。257760 0。863664 1。237688 1。599834g -0。843632 0。202047 -0。175664 -0。525140h -2。419964 0。264638 0。149577 -0。319869”“”

判斷:

print(df。loc[‘a’]>0)“”“輸出: TrueB TrueC FalseD TrueName: a, dtype: bool”“”

2)iloc[]函式

:透過行號來取行資料。中括號裡面也是先行後列,行列標籤用逗號分割,與loc不同的之處是,。iloc 是根據行數與列數來索引的。

df = pd。DataFrame(np。random。randn(8, 4), columns = [‘A’, ‘B’, ‘C’, ‘D’])print(df)print(df。iloc[:4]) # 取前四列資料print(df。iloc[2:5, 2:4]) # 行:取第3行到第5行資料,列:取第3列到底4列資料“”“輸出: A B C D0 -2。244208 0。289247 -0。610394 0。1220741 -0。567245 -0。981979 0。745125 0。3073822 -0。413786 0。057957 1。369953 -0。5915333 -0。284472 0。208514 -0。754006 -1。9908314 0。579098 -0。351095 -1。097065 -2。7172865 1。391632 1。000434 -0。025586 0。7137316 0。030316 0。407541 2。015870 -0。5503947 -0。450774 -0。293389 -0。053082 0。098550

print(df。iloc[:4]) # 取前四列資料 A B C D0 -2。244208 0。289247 -0。610394 0。1220741 -0。567245 -0。981979 0。745125 0。3073822 -0。413786 0。057957 1。369953 -0。5915333 -0。284472 0。208514 -0。754006 -1。990831print(df。iloc[2:5, 2:4]) # 行:取第3行到第5行資料,列:取第3列到底4列資料 C D2 1。369953 -0。5915333 -0。754006 -1。9908314 -1。097065 -2。717286

”“”

df = pd。DataFrame(np。random。randn(8, 4), columns = [‘A’, ‘B’, ‘C’, ‘D’])

print(df。iloc[[1, 3, 5], [1, 3]])print( df。iloc[1:3, :])print( df。iloc[:,1:3])“”“輸出: B D1 1。079715 0。4716543 -0。440755 -0。7168785 1。161093 0。860139 A B C D1 -0。062004 1。079715 -0。769709 0。4716542 -1。617348 0。942890 -1。416927 -0。494119 B C0 -0。854684 -0。4619401 1。079715 -0。7697092 0。942890 -1。4169273 -0。440755 1。0152764 0。848106 0。3998295 1。161093 -0。4477376 0。740808 0。7565447 0。201873 0。117193”“”

3) ix[]函式

:兼備了lo和iloc兩種方法(現在多棄用了)

import pandas as pdimport numpy as np

df = pd。DataFrame(np。random。randn(8, 4), columns = [‘A’, ‘B’, ‘C’, ‘D’])print(df。ix[:4],‘\n’)print(df。ix[:, ‘A’])“”“輸出: A B C D0 -0。823268 0。388715 0。015230 -1。5262251 0。706624 -0。644479 -0。764379 0。9498152 1。039163 -0。033233 -0。104077 0。6174753 0。425551 -1。141799 -0。326049 -0。7209354 0。872313 1。017448 -0。653088 0。128724

0 -0。8232681 0。7066242 1。0391633 0。4255514 0。8723135 -1。7907406 -0。2706517 0。167843Name: A, dtype: float64”“”

4) 直接選擇[]

# 直接選擇[]import pandas as pdimport numpy as np

df = pd。DataFrame(np。random。randn(8, 4), columns = [‘A’, ‘B’, ‘C’, ‘D’])print(df[‘A’],‘\n’)print(df[[‘A’,‘B’]],‘\n’)print(df[2:2])“”“輸出:

0 -1。4589881 -0。7707302 -0。2630543 -0。2446804 0。5666925 -1。9356846 1。9715957 -1。229495Name: A, dtype: float64

A B0 -1。458988 -0。5612271 -0。770730 0。4306202 -0。263054 -1。2775153 -0。244680 0。2413424 0。566692 -0。4698775 -1。935684 1。1922636 1。971595 -0。3684457 -1。229495 0。871946

Empty DataFrameColumns: [A, B, C, D]Index: []”“”

5) 屬性訪問

# 屬性訪問import pandas as pdimport numpy as npdf = pd。DataFrame(np。random。randn(8, 4), columns = [‘A’, ‘B’, ‘C’, ‘D’])

print(df。A)“”“輸出:00。6457221-0。7864662-0。42435231。83814341。16359651。4367976-0。75638870。353392Name: A, dtype: float64”“”

頂部