根据拆分后拆分的字符串中的元素筛选行(Pandas)

2024-10-02 12:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个PandasDataFrame,其中包含一个以分号分隔的位置名的列:

index   locations
39951   Credit; Mount Pleasant GO
40976   Ajax GO; Whitby GO; Credit; Oshawa GO; Bayly
14961   Credit; Mount Pleasant GO; Port Credit GO
...

我想做的是根据指定位置是否出现在分号分隔的列表中进行筛选,首先拆分字符串(在;上),然后检查列表中是否有位置

在这里使用str.contains()不起作用,因为有重叠的位置名(Credit出现在CreditPort Credit中,例如),并且具有单个位置的行将没有;,因此我无法搜索Credit;。我试过这样的方法

df["Credit" in df.locations.str.split("; ")]

但这似乎不起作用

有什么建议吗


Tags: godf列表indexportajaxcreditmount
2条回答

您可以使用regex(^|;) *Credit(;|$)来确保模式在分隔符之间是独占的,因此Credit将位于字符串的开头或结尾,或者直接跟在分隔符;后面:

df
   index                                     locations
0  39951                     Credit; Mount Pleasant GO
1  40976  Ajax GO; Whitby GO; Credit; Oshawa GO; Bayly
2  14961             Mount Pleasant GO; Port Credit GO

df.locations.str.contains('(^|;) *Credit(;|$)')
#0     True
#1     True
#2    False
#Name: locations, dtype: bool

如果要进一步忽略大小写,请将修饰符?i添加到模式中:

df.locations.str.contains('(?i)(^|;) *credit(;|$)')
#0     True
#1     True
#2    False
#Name: locations, dtype: bool

您可以尝试(不使用正则表达式):

#split and explode the dataframe:
m=df['locations'].str.split('; ').explode()
#check your condition and get index where condition satisfies:
m=m[m.isin(['Credit'])].index.unique()
#Finally filter out dataframe:
out=df.loc[m]

现在,如果您打印out,您将得到经过筛选的数据帧

相关问题 更多 >

    热门问题