我有一个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
出现在Credit
和Port Credit
中,例如),并且具有单个位置的行将没有;
,因此我无法搜索Credit;
。我试过这样的方法
df["Credit" in df.locations.str.split("; ")]
但这似乎不起作用
有什么建议吗
您可以使用regex
(^|;) *Credit(;|$)
来确保模式在分隔符之间是独占的,因此Credit将位于字符串的开头或结尾,或者直接跟在分隔符;
后面:如果要进一步忽略大小写,请将修饰符
?i
添加到模式中:您可以尝试(不使用正则表达式):
现在,如果您打印
out
,您将得到经过筛选的数据帧相关问题 更多 >
编程相关推荐