如果列值(字符串)包含python集合中的任何值,如何过滤数据框行? [英] How to filter dataframe rows if column value (string) contains any of the values in a set in python?
问题描述
如果单元格字符串包含预定义集中的任何值,我想过滤行.
I want to filter rows if cell string contains anyone of the values in the predefined set.
例如,对于以下数据框:
For example, for following dataframe:
ids ids2 vals
0 a h a i 1
1 b z n a 2
2 f z c a 3
3 n i n h 4
我要提取以下行(在id列中具有"h"或"i"的行):
I want following rows extracted (the rows which have 'h' or 'i' in the ids column):
ids ids2 vals
0 a h a i 1
3 n i n h 4
生成数据框的代码:
d = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a h', 'b z', 'f z', 'n i'],'ids2': ['a i', 'n a', 'c a', 'n h']})
到目前为止我所做的:
d[d['ids'].str.contains('h')|d['ids'].str.contains('i')]
此处,预定义的集合很小,并且包含的内容区分大小写.有没有办法我可以不区分大小写或使用某些列表包含方法来做到这一点.我尝试这样做:
Here the predefined set is small and contains is case sensitive. Is there a way I can do this either with case-insensitivity or using some list contains method. I tried doing this:
d[len(re.findall('h|i',d['ids'].str,re.IGNORECASE)) > 0]
但是它给了我TypeError: expected string or bytes-like object
.
或者这个:
data[any(d['name'].str.contains(x) for x in ['h','i'])]
给出错误:KeyError: 'name'
有人可以帮我吗?
gives error: KeyError: 'name'
Can someone help me with this?
推荐答案
使用case = False
使其不区分大小写:
Use case = False
to make it case-insensitive:
d[d['ids'].str.contains('h', case=False)|d['ids'].str.contains('i',case=False)]
这绝对是一个环形交叉路口,但它可以正常工作:
This is definitely a little roundabout but it will work:
letters = ['h', 'i']
d[d['ids'].str.split().apply(lambda x: len(set(x).intersection(set(letters))))>0]
这篇关于如果列值(字符串)包含python集合中的任何值,如何过滤数据框行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!