如何在Python中过滤数据帧中以整数开头的列?
我使用了以下代码:如何在Python中过滤数据帧中以整数开头的列?,python,python-3.x,pandas,dataframe,data-science,Python,Python 3.x,Pandas,Dataframe,Data Science,我使用了以下代码: data_snp_old=data_snp_age[data_snp_age['Age'].str.contains('15+', na = False)] data_snp_old=data_snp_age.filter(regex='^15+', axis=0) 代码工作不完美,即它们正在过滤,但某些行具有问题在于您在contains()函数中使用的表达式。与其将“15+”视为字符序列,不如将其视为正则表达式。因此,它符合这两个条件 功能定义: Series.str.
data_snp_old=data_snp_age[data_snp_age['Age'].str.contains('15+', na = False)]
data_snp_old=data_snp_age.filter(regex='^15+', axis=0)
代码工作不完美,即它们正在过滤,但某些行具有问题在于您在
contains()
函数中使用的表达式。与其将“15+”视为字符序列,不如将其视为正则表达式。因此,它符合这两个条件
功能定义:
Series.str.contains(pat,case=True,flags=0,na=nan,regex=True)
以下是您可以做的:
import pandas as pd
# Making a toy data-set.
data={'Category':['Age','Age','Age','Age','Age'],'Age':['15+','<15','15+','<15','15+']}
df= pd.DataFrame(data=data)
print(df)
# Output:
Category Age
0 Age 15+
1 Age <15
2 Age 15+
3 Age <15
4 Age 15+
或
df_new=df[df['Age'].str.contains(r'(\d{2}\+)', na = False)]
# the above regex matches a group in which two digits should be followed by a +
print(df_new)
# Output:
Category Age
0 Age 15+
2 Age 15+
4 Age 15+
以下是一些内容供进一步参考:
希望这有帮助,干杯您的年龄列是一个字符串,因此无法使用整数逻辑对其进行筛选,您想做什么?抓取我正在使用str.contain()的所有
行,但结果仍然没有给出所有年龄为15岁以上的行。我试图过滤掉所有年龄为15岁以上的行。@AvinashKr请将数据框和预期输出作为文本发布。它将帮助你更快地获得帮助。
df_new=df[df['Age'].str.contains('15+', na = False,regex=False)]
# Tell contains() to not consider the expression as a regex by default.
print(df_new)
# Output:
Category Age
0 Age 15+
2 Age 15+
4 Age 15+
df_new=df[df['Age'].str.contains(r'(\d{2}\+)', na = False)]
# the above regex matches a group in which two digits should be followed by a +
print(df_new)
# Output:
Category Age
0 Age 15+
2 Age 15+
4 Age 15+