使用Pandas选择包含特定文本的行

使用Pandas选择包含特定文本的行

在使用pandas数据框架进行数据预处理时,可能需要找到包含特定文本的行。在这篇文章中,我们将讨论在pandas数据框架的列或行中找到包含特定文本的行的方法。

使用中的数据集:

job Age_Range Salary Credit-Rating Savings Buys_Hone
Own Middle-aged High Fair 10000 Yes
Govt Young Low Fair 15000 No
Private Senior Average Excellent 20000 Yes
Own Middle-aged High Fair 13000 No
Own Young Low Excellent 17000 Yes
Private Senior Average Fair 18000 No
Govt Young Average Fair 11000 No
Private Middle-aged Low Excellent 9000 No
Govt Senior High Excellent 14000 Yes

方法1:使用contains()

使用字符串的contains()函数来过滤行。我们根据数据框架中的 “Credit-Rating “列过滤行,将其转换为字符串,然后使用字符串类的contains方法。

示例:

# importing pandas as pd
import pandas as pd
  
# reading csv file
df = pd.read_csv("Assignment.csv")
  
# filtering the rows where Credit-Rating is Fair
df = df[df['Credit-Rating'].str.contains('Fair')]
print(df)
Python

输出 :

使用Pandas选择包含特定文本的行

含有公平为储蓄的行

方法2:使用itertuples()

使用itertuples()方法对行进行迭代查找,以获得包含所需文本的行。itertuple方法返回一个迭代器,为DataFrame中的每一行产生一个命名的元组。它比pandas的iterrows()方法工作得更快。

示例:

# importing pandas as pd
import pandas as pd
  
# reading csv file
df = pd.read_csv("Assignment.csv")
  
# filtering the rows where Age_Range contains Young
for x in df.itertuples():
    if x[2].find('Young') != -1:
        print(x)
Python

输出 :

使用Pandas选择包含特定文本的行

年龄范围为Young的行

方法3:使用iterrows()

使用iterrows()函数对行进行迭代查找,以获得包含所需文本的行。iterrows()函数返回产生每个索引值的迭代器,以及包含每行数据的序列。与itertuples相比,它的速度较慢,因为它要进行大量的类型检查。

示例:

# importing pandas as pd
import pandas as pd
  
# reading csv file
df = pd.read_csv("Assignment.csv")
  
# filtering the rows where job is Govt
for index, row in df.iterrows():
    if 'Govt' in row['job']:
        print(index, row['job'], row['Age_Range'],
              row['Salary'], row['Savings'], row['Credit-Rating'])
Python

输出 :

使用Pandas选择包含特定文本的行

工作为Govt的行

方法4:使用正则表达式

使用正则表达式来寻找具有所需文本的行。 search()是re.search(pattern, string)模块的一个方法。它类似于re.match(),但它并不限制我们只在字符串的开头寻找匹配。我们在每一行上进行迭代,在每一个索引上的工作与’Govt’进行比较,只选择那些行。

示例:

# using regular expressions
from re import search
  
# import pandas as pd
import pandas as pd
  
# reading CSV file
df = pd.read_csv("Assignment.csv")
  
# iterating over rows with job as Govt and printing
for ind in df.index:
    if search('Govt', df['job'][ind]):
        print(df['job'][ind], df['Savings'][ind],
              df['Age_Range'][ind], df['Credit-Rating'][ind])
Python

输出 :

使用Pandas选择包含特定文本的行

工作是Govt的行

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册