删除不以特定单词开头/包含特定单词的行

时间:2020-06-04 18:44:27

标签: python regex pandas dataframe

我有以下输出

Age
'1 year old',
'14 years old', 
'music store', 
'7 years old ',
'16 years old ',

在使用此行代码后创建

df['Age']=df['Age'].str.split('.', expand=True,n=0)[0]
df['Age'].tolist()

我想从数据集中删除不是以数字或数字+年+年或数字+年+开始的行(最好使用它的副本或在过滤后使用新的行)旧。

预期产量

Age (in a new dataset filtered)
'1 year old',
'14 years old', 
'7 years old ',
'16 years old ',

我该怎么办?

2 个答案:

答案 0 :(得分:0)

使用Series.str.contains并创建一个布尔掩码来过滤数据框:

m = df['Age'].str.contains(r'(?i)^\d+\syears?\sold')
df1 = df[m]

结果:

# print(df1)
             Age
0     1 year old
1   14 years old 
3    7 years old
4   16 years old

您可以测试正则表达式模式here

答案 1 :(得分:0)

下面的代码查找以撇号开头,后跟数字的文本,并且仅保留这些行:

df = pd.read_clipboard(sep=';')


df.loc[df.Age.str.match("\'\d+")]

            Age
0   '1 year old',
1   '14 years old',
3   '7 years old ',
4   '16 years old ',

请注意,这仅限于单引号和数字,@ Shubham的解决方案涵盖了更多