如何从Python中的整数开始过滤数据框中的列?

问题描述 投票:0回答:1

我使用了以下代码:

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)

这些代码无法正常工作,即它们正在过滤,但还会出现一些带有<15个输入项的行。

enter image description here

python python-3.x pandas dataframe data-science
1个回答
0
投票

这里的问题是您在contains()函数中使用的表达式。与其将“ 15+”视为字符序列,不如将其视为正则表达式。因此,它符合两个条件。

功能定义:Series.str.contains(pat, case=True, flags=0, na=nan, regex=True)

Parameter :
pat : Character sequence or regular expression.
case : If True, case sensitive.
flags : Flags to pass through to the re module, e.g. re.IGNORECASE.
na : Fill value for missing values.
regex : If True, assumes the pat is a regular expression.

Returns : Series or Index of boolean values 

这是您可以做的:

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('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+

这里有一些东西需要进一步参考:

希望这会有所帮助,欢呼!

© www.soinside.com 2019 - 2024. All rights reserved.