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