從網絡采集來的數據集往往是雜亂無章的,而使用 Python 處理字符串往往是比較容易的,Pandas 同樣提供了一系列向量化字符串操作方法
-
一、Pandas字符串操作:.str
假設有以下的 Series 實例:
如果用函數向量化的方法,對上面的 Series 中的字符串進行處理,比如所有單詞的首寫字母都轉化為大寫,是可行的,但是如果 Series 中的字符串包含缺失值,就需要進一步修改向量化的函數,比較繁瑣,此時,對字符串進行處理最快速的是使用 Pandas 的字符串操作方法:
Series 還有一些字符串的切片以及合並操作,都可以通過 .str 的方法來調用:
-
二、Pandas 字符串方法列表
Pandas 絕大多數字符串方法都跟 Python 字符串方法很相似
- 字符長度
- len()
- 字符檢索
- find()
- rfind()
- 字符轉換
- lower()
- upper():
- title:將每個單詞的第一個字符轉換為大寫和保持小寫
- capitalize():將第一個字符轉換為大寫字母保持小寫
- swapcase() :將大寫轉換為小寫,小寫轉換為大寫
- translate()
- 字符替換
- replace()
- 字符類型判斷
- islower()
- isupper()
- isnumeric()
- isalnum()
- isdecimal()
- isalpha()
- isdigit()
- isspace()
- istitle()
- 字符調整
- ljust()
- rjust()
- 字符對齊與填充
- startswith()
- endswith()
- center()
- zfill()
- 字符檢索
- index()
- rindex()
- find()
- 字符切割
- split()
- rsplit()
- partition()
- rpartition()
- 字符整理
- strip()
- rstrip()
- lstrip()
-
三、使用頻率最高的方法
-
1、.replace()
-
2、.split()
-
3、.strip()
-
四、使用頻率較低的方法
-
1、字符轉化:.str.translate()
注:ord()函數主要用來返回對應字符的ascii碼,chr()主要用來表示ascii碼對應的字符他的輸入時數字,可以用十進制,也可以用十六進制
-
2、字符調整:.str.ljust() 和 .str.rjust()
-
3、字符開頭結尾與填充:.str.startswith(),.str.endswith(),.str.center(),.str.zfill()
-
4、字符檢索:.str.index(),.str.rindex(),.str.find()
.str.index() 和 .str.rindex() 方法無法在 Series 中找到包含字符的字符串,即只能找某一個字符,且必須整個 Series 里所有非空字符串中都包含要查找的字符,否則就會報錯:
用 .str.find() ,找不到檢索字符的話,將會返回-1,且可以查找多個字符: