網(wǎng)站首頁 編程語言 正文
以下內(nèi)容,如何使用pandas提取含有指定字符串的行的方法進(jìn)行解釋說明。
行的提取(選擇)方法
完全匹配
- ==
部分匹配
- str.contains():包含一個特定的字符串
- 參數(shù)na:缺少值NaN處理
- 參數(shù)case:大小寫我的處理
- 參數(shù)regex:使用正則表達(dá)式模式
- str.endswith():以特定字符串結(jié)尾
- str.startswith():以特定的字符串開頭
- 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的話,只能提取(選擇)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
請注意,默認(rèn)情況下,第一個參數(shù)中指定的字符串將作為正則表達(dá)式模式進(jìn)行處理,如下所述。
參數(shù)na:缺少值NaN處理
如果元素是缺失值NaN,則默認(rèn)情況下它將返回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:大小寫我的處理
默認(rèn)情況下,區(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:使用正則表達(dá)式模式
使用str.contains()時要記住的一件事是,默認(rèn)情況下,指定為第一個參數(shù)的字符串將作為正則表達(dá)式模式進(jìn)行處理。
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
例如,如果要判斷是否包含正則表達(dá)式的特殊字符,例如?,。,*,則需要設(shè)置regex = False。當(dāng)然,可以指定一個正則表達(dá)式模式,以轉(zhuǎn)義\?等特殊字符。
請注意,默認(rèn)值可能會導(dǎo)致錯誤。
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)志。如稍后所述,還有對應(yīng)于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的行,則設(shè)置na = True;如果不想選擇,則將na = False設(shè)置。
沒有參數(shù)case,因此它始終區(qū)分大小寫。
另外,第一個參數(shù)的字符串在確定中照原樣使用,而不作為正則表達(dá)式模式處理。
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():匹配正則表達(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()對應(yīng)于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
當(dāng)需要確定是否包括與模式匹配的部分時,不僅在開始時,而且默認(rèn)使用與上述re.search()等效的re.contains()(regex = True)。
str.match()與str.contains()可以以相同的方式指定參數(shù)na,case和flag。
原文鏈接:https://blog.csdn.net/qq_18351157/article/details/105362159
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2022-08-25 C++超詳細(xì)梳理IO流操作_C 語言
- 2022-06-18 Redis實現(xiàn)單設(shè)備登錄的場景分析_Redis
- 2022-10-10 python使用pandas讀寫excel文件的方法實例_python
- 2022-01-17 rabbitmq出現(xiàn) 已安裝 rabbitmq-server 軟件包 post-installati
- 2022-06-02 一篇文章帶你了解Python中的裝飾器_python
- 2022-06-22 Git用戶簽名的修改取消及優(yōu)先級拓展教程_其它綜合
- 2022-11-03 anaconda?部署Jupyter?Notebook服務(wù)器過程詳解_python
- 2024-02-28 UNI-APP中,swiper和tabbar結(jié)合實現(xiàn)滑動翻頁效果
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支