Pandas提取含有指定字符串的行(完全匹配,部分匹配)
以下內(nèi)容,如何使用pandas提取含有指定字符串的行的方法進行解釋說明。
行的提?。ㄟx擇)方法
完全匹配
- ==
部分匹配
- str.contains():包含一個特定的字符串
- 參數(shù)na:缺少值NaN處理
- 參數(shù)case:大小寫我的處理
- 參數(shù)regex:使用正則表達式模式
- str.endswith():以特定字符串結(jié)尾
- str.startswith():以特定的字符串開頭
- str.match():匹配正則表達式模式
要提取部分匹配的行,可以使用pandas的(str.xxx())方法,根據(jù)指定條件提取的字符串方法。
這次以以下數(shù)據(jù)為例
import pandas as pd df = pd.read_csv('./data/08/sample_pandas_normal.csv').head(3) print(df) # ? ? ? name ?age state ?point # 0 ? ?Alice ? 24 ? ?NY ? ? 64 # 1 ? ? ?Bob ? 42 ? ?CA ? ? 92 # 2 ?Charlie ? 18 ? ?CA ? ? 70
行的提?。ㄟx擇)方法
首先,展示如何從pandas.DataFrame中提?。ㄟx擇)行以獲得新的pandas.DataFrame。
使用布爾值的布爾列表(數(shù)組)或pandas.Series的話,只能提取(選擇)True行。
mask = [True, False, True] df_mask = df[mask] print(df_mask) # name age state point # 0 Alice 24 NY 64 # 2 Charlie 18 CA 70
因此,對于具有字符串元素的列,是否能夠獲得根據(jù)條件的布爾列表就足夠了。
完全匹配
==
如果元素與字符串完全匹配,則使用==獲取為True的pandas.Series。
print(df['state'] == 'CA') # 0 ? ?False # 1 ? ? True # 2 ? ? True # Name: state, dtype: bool print(df[df['state'] == 'CA']) # ? ? ? name ?age state ?point # 1 ? ? ?Bob ? 42 ? ?CA ? ? 92 # 2 ?Charlie ? 18 ? ?CA ? ? 70
部分匹配
str.contains():包含一個特定的字符串
pandas.Series字符串方法str.contains()允許獲取包含特定字符串的pandas.Series.
print(df['name'].str.contains('li')) # 0 ? ? True # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool print(df[df['name'].str.contains('li')]) # ? ? ? name ?age state ?point # 0 ? ?Alice ? 24 ? ?NY ? ? 64 # 2 ?Charlie ? 18 ? ?CA ? ? 70
請注意,默認情況下,第一個參數(shù)中指定的字符串將作為正則表達式模式進行處理,如下所述。
參數(shù)na:缺少值NaN處理
如果元素是缺失值NaN,則默認情況下它將返回NaN而不是True或False。因此,使用pandas.Series提取該行是錯誤的。
df_nan = df.copy() df_nan.iloc[2, 0] = float('nan') print(df_nan) # ? ? name ?age state ?point # 0 ?Alice ? 24 ? ?NY ? ? 64 # 1 ? ?Bob ? 42 ? ?CA ? ? 92 # 2 ? ?NaN ? 18 ? ?CA ? ? 70 print(df_nan['name'].str.contains('li')) # 0 ? ? True # 1 ? ?False # 2 ? ? ?NaN # Name: name, dtype: object # print(df_nan[df_nan['name'].str.contains('li')]) # ValueError: cannot index with vector containing NA / NaN values
可以通過str.contains()的參數(shù)na來指定替換NaN結(jié)果的值。
print(df_nan['name'].str.contains('li', na=False)) # 0 ? ? True # 1 ? ?False # 2 ? ?False # Name: name, dtype: bool print(df_nan['name'].str.contains('li', na=True)) # 0 ? ? True # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool
用作條件時,如果na = True,則選擇NaN的行,如果na = False,則不選擇NaN的行。
參數(shù)case:大小寫我的處理
默認情況下,區(qū)分大小寫。如果參數(shù)case為False,則case被忽略。
print(df['name'].str.contains('LI')) # 0 ? ?False # 1 ? ?False # 2 ? ?False # Name: name, dtype: bool print(df['name'].str.contains('LI', case=False)) # 0 ? ? True # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool
參數(shù)regex:使用正則表達式模式
使用str.contains()時要記住的一件事是,默認情況下,指定為第一個參數(shù)的字符串將作為正則表達式模式進行處理。
print(df['name'].str.contains('i.*e')) # 0 True # 1 False # 2 True # Name: name, dtype: bool
如果參數(shù)ragex為False,則確定是否包含第一個參數(shù)的字符串本身。
print(df['name'].str.contains('i.*e', regex=False)) # 0 False # 1 False # 2 False # Name: name, dtype: bool
例如,如果要判斷是否包含正則表達式的特殊字符,例如?,。,*,則需要設置regex = False。當然,可以指定一個正則表達式模式,以轉(zhuǎn)義\?等特殊字符。
請注意,默認值可能會導致錯誤。
df_q = df.copy() df_q.iloc[2, 0] += '?' print(df_q) # ? ? ? ?name ?age state ?point # 0 ? ? Alice ? 24 ? ?NY ? ? 64 # 1 ? ? ? Bob ? 42 ? ?CA ? ? 92 # 2 ?Charlie? ? 18 ? ?CA ? ? 70 # print(df_q['name'].str.contains('?')) # error: nothing to repeat at position 0 print(df_q['name'].str.contains('?', regex=False)) # 0 ? ?False # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool print(df_q['name'].str.contains('\?')) # 0 ? ?False # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool
str.contains()等同于re.search(),并且可以在flags參數(shù)中指定正則表達式標志。如稍后所述,還有對應于re.match()的str.match()。
請注意,下面要介紹的str.endswith()如果想要確定end ?,會更容易,如本例所示。
str.endswith():以特定字符串結(jié)尾
pandas.Series字符串方法str.endswith()可以獲取以特定字符串結(jié)尾的pandas.Series。
print(df['name'].str.endswith('e')) # 0 ? ? True # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool print(df[df['name'].str.endswith('e')]) # ? ? ? name ?age state ?point # 0 ? ?Alice ? 24 ? ?NY ? ? 64 # 2 ?Charlie ? 18 ? ?CA ? ? 70
str.endswith()也有一個參數(shù)na。如果要選擇缺失值NaN的行,則設置na = True;如果不想選擇,則將na = False設置。
沒有參數(shù)case,因此它始終區(qū)分大小寫。
另外,第一個參數(shù)的字符串在確定中照原樣使用,而不作為正則表達式模式處理。
str.startswith():以特定的字符串開頭
pandas.Series字符串方法str.startswith()可以獲取以特定字符串開頭的pandas.Series。
print(df['name'].str.startswith('B')) # 0 ? ?False # 1 ? ? True # 2 ? ?False # Name: name, dtype: bool print(df[df['name'].str.startswith('B')]) # ? name ?age state ?point # 1 ?Bob ? 42 ? ?CA ? ? 92
str.match():匹配正則表達式模式
pandas.Series字符串方法str.match()可以獲取與正則表達式模式匹配的pandas.Series。
print(df['name'].str.match('.*i.*e')) # 0 ? ? True # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool print(df[df['name'].str.match('.*i.*e')]) # ? ? ? name ?age state ?point # 0 ? ?Alice ? 24 ? ?NY ? ? 64 # 2 ?Charlie ? 18 ? ?CA ? ? 70
如上所述,str.match()對應于re.match(),并確定字符串的開頭是否與模式匹配。如果不是一開始就為False。
print(df['name'].str.match('.*i')) # 0 ? ? True # 1 ? ?False # 2 ? ? True # Name: name, dtype: bool print(df['name'].str.match('i.*e')) # 0 ? ?False # 1 ? ?False # 2 ? ?False # Name: name, dtype: bool
當需要確定是否包括與模式匹配的部分時,不僅在開始時,而且默認使用與上述re.search()等效的re.contains()(regex = True)。
str.match()與str.contains()可以以相同的方式指定參數(shù)na,case和flag。
到此這篇關(guān)于Pandas提取含有指定字符串的行(完全匹配,部分匹配)的文章就介紹到這了,更多相關(guān)Pandas提取指定字符串的行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python網(wǎng)頁請求urllib2模塊簡單封裝代碼
這篇文章主要分享一個python網(wǎng)頁請求模塊urllib2模塊的簡單封裝代碼,有需要的朋友參考下2014-02-02pyqt5 comboBox獲得下標、文本和事件選中函數(shù)的方法
今天小編就為大家分享一篇pyqt5 comboBox獲得下標、文本和事件選中函數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06python實現(xiàn)ModBusTCP協(xié)議的client功能
Modbus TCP 是一種基于 TCP/IP 協(xié)議棧的 Modbus 通信協(xié)議,它用于在工業(yè)自動化系統(tǒng)中進行設備之間的通信,只要通過pymodbus或pyModbusTCP任意模塊就可以實現(xiàn),本文采用pymodbus,感興趣的朋友跟隨小編一起看看吧2023-10-10Python編程pygame模塊實現(xiàn)移動的小車示例代碼
這篇文章主要介紹了Python編程pygame模塊實現(xiàn)移動的小車示例代碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01python通過pip更新所有已安裝的包實現(xiàn)方法
下面小編就為的帶來一篇python通過pip更新所有已安裝的包實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05