Pandas字符串和文本數據


在本章中,我們將使用基本系列/索引來討論字符串操作。在隨后的章節中,將學習如何將這些字符串函數應用於數據幀(DataFrame)。

Pandas提供了一組字符串函數,可以方便地對字符串數據進行操作。 最重要的是,這些函數忽略(或排除)丟失/NaN值。

幾乎這些方法都使用Python字符串函數(請參閱: http://docs.python.org/3/library/stdtypes.html#string-methods )。 因此,將Series對象轉換為String對象,然后執行該操作。

下面來看看每個操作的執行和說明。

編號 函數 描述
1 lower() Series/Index中的字符串轉換為小寫。
2 upper() Series/Index中的字符串轉換為大寫。
3 len() 計算字符串長度。
4 strip() 幫助從兩側的系列/索引中的每個字符串中刪除空格(包括換行符)。
5 split(' ') 用給定的模式拆分每個字符串。
6 cat(sep=' ') 使用給定的分隔符連接系列/索引元素。
7 get_dummies() 返回具有單熱編碼值的數據幀(DataFrame)。
8 contains(pattern) 如果元素中包含子字符串,則返回每個元素的布爾值True,否則為False
9 replace(a,b) 將值a替換為值b
10 repeat(value) 重復每個元素指定的次數。
11 count(pattern) 返回模式中每個元素的出現總數。
12 startswith(pattern) 如果系列/索引中的元素以模式開始,則返回true
13 endswith(pattern) 如果系列/索引中的元素以模式結束,則返回true
14 find(pattern) 返回模式第一次出現的位置。
15 findall(pattern) 返回模式的所有出現的列表。
16 swapcase 變換字母大小寫。
17 islower() 檢查系列/索引中每個字符串中的所有字符是否小寫,返回布爾值
18 isupper() 檢查系列/索引中每個字符串中的所有字符是否大寫,返回布爾值
19 isnumeric() 檢查系列/索引中每個字符串中的所有字符是否為數字,返回布爾值。

現在創建一個系列,看看上述所有函數是如何工作的。

import pandas as pd import numpy as np s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) print (s) 
Python

執行上面示例代碼,得到以下結果 -

0             Tom
1    William Rick
2            John
3         Alber@t
4             NaN
5            1234
6      SteveMinsu
dtype: object
Shell

1. lower()函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) print (s.str.lower()) 
Python

執行上面示例代碼,得到以下結果 -

0             tom
1    william rick
2            john
3         alber@t
4             NaN
5            1234
6      steveminsu
dtype: object
Shell

2. upper()函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) print (s.str.upper()) 
Python

執行上面示例代碼,得到以下結果 -

0             TOM
1    WILLIAM RICK
2            JOHN
3         ALBER@T
4             NaN
5            1234
6      STEVESMITH
dtype: object
Shell

3. len()函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) print (s.str.len()) 
Python

執行上面示例代碼,得到以下結果 -

0     3.0
1    12.0
2     4.0
3     7.0
4     NaN
5     4.0
6    10.0
dtype: float64
Shell

4. strip()函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s) print ("=========== After Stripping ================") print (s.str.strip()) 
Python

執行上面示例代碼,得到以下結果 -

0             Tom 
1     William Rick
2             John
3          Alber@t
dtype: object
=========== After Stripping ================
0             Tom
1    William Rick
2            John
3         Alber@t
dtype: object
Shell

5. split(pattern)函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s) print ("================= Split Pattern: ==================") print (s.str.split(' ')) 
Python

執行上面示例代碼,得到以下結果 -

0             Tom 
1     William Rick
2             John
3          Alber@t
dtype: object
================= Split Pattern: ==================
0              [Tom, ]
1    [, William, Rick]
2               [John]
3            [Alber@t]
dtype: object
Shell

6. cat(sep=pattern)函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s.str.cat(sep=' <=> ')) 
Python

執行上面示例代碼,得到以下結果 -

Tom  <=>  William Rick <=> John <=> Alber@t
Shell

7. get_dummies()函數示例

import pandas as pd import numpy as np s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s.str.get_dummies()) 
Python

執行上面示例代碼,得到以下結果 -

    William Rick  Alber@t  John  Tom 
0              0        0     0     1
1              1        0     0     0
2              0        0     1     0
3              0        1     0     0
Shell

8. contains()函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s.str.contains(' ')) 
Python

執行上面示例代碼,得到以下結果 -

0     True
1     True
2    False
3    False
dtype: bool
Shell

9. replace(a,b)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s) print ("After replacing @ with $: ============== ") print (s.str.replace('@','$')) 
Python

執行上面示例代碼,得到以下結果 -

0             Tom 
1     William Rick
2             John
3          Alber@t
dtype: object
After replacing @ with $: ============== 
0             Tom 
1     William Rick
2             John
3          Alber$t
dtype: object
Shell

10. repeat(value)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s.str.repeat(2)) 
Python

執行上面示例代碼,得到以下結果 -

0                      Tom Tom 
1     William Rick William Rick
2                      JohnJohn
3                Alber@tAlber@t
dtype: object
Shell

11. count(pattern)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print ("The number of 'm's in each string:") print (s.str.count('m')) 
Python

執行上面示例代碼,得到以下結果 -

The number of 'm's in each string:
0    1
1    1
2    0
3    0
dtype: int64
Shell

12. startswith(pattern)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print ("Strings that start with 'T':") print (s.str. startswith ('T')) 
Python

執行上面示例代碼,得到以下結果 -

Strings that start with 'T':
0     True
1    False
2    False
3    False
dtype: bool
Shell

13. endswith(pattern)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print ("Strings that end with 't':") print (s.str.endswith('t')) 
Python

執行上面示例代碼,得到以下結果 -

Strings that end with 't':
0    False
1    False
2    False
3     True
dtype: bool
Shell

14. find(pattern)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s.str.find('e')) 
Python

執行上面示例代碼,得到以下結果 -

0   -1
1   -1
2   -1
3    3
dtype: int64
Shell

注意:-1表示元素中沒有這樣的模式可用。

15. findall(pattern)函數示例

import pandas as pd s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) print (s.str.findall('e')) 
Python

執行上面示例代碼,得到以下結果 -

0     []
1     []
2     []
3    [e]
dtype: object
Shell

空列表([])表示元素中沒有這樣的模式可用。

16. swapcase()函數示例

import pandas as pd s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t']) print (s.str.swapcase()) 
Python

執行上面示例代碼,得到以下結果 -

0             tOM
1    wILLIAM rICK
2            jOHN
3         aLBER@T
dtype: object
Shell

17. islower()函數示例

import pandas as pd s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t']) print (s.str.islower()) 
Python

執行上面示例代碼,得到以下結果 -

0    False
1    False
2    False
3    False
dtype: bool
Shell

18. isupper()函數示例

import pandas as pd s = pd.Series(['TOM', 'William Rick', 'John', 'Alber@t']) print (s.str.isupper()) 
Python

執行上面示例代碼,得到以下結果 -

0    True
1    False
2    False
3    False
dtype: bool
Shell

19. isnumeric()函數示例

import pandas as pd s = pd.Series(['Tom', '1199','William Rick', 'John', 'Alber@t']) print (s.str.isnumeric()) 
Python

執行上面示例代碼,得到以下結果 -

0    False
1     True
2    False
3    False
4    False
dtype: bool


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM