简体   繁体   English

如何基于以列表为值的列在Pandas数据框中过滤行?

[英]How do I filter for rows in a Pandas dataframe based on a column that has list as values?

I have a Pandas dataframe where one of the columns stores lists of string literals. 我有一个Pandas数据框,其中的一列存储字符串文字列表。 For example, my data looks like the following. 例如,我的数据如下所示。

field1, field2
x1, ['tag1', 'tag2']
x2, ['tag1', 'tag3']

I want to get only the records in this dataframe whose field2 list contains tag1 or tag2 . 我只想获取此dataframe中其field2列表包含tag1tag2 So, in the example above, only the record where field1=x1 should be returned. 因此,在上面的示例中,仅应返回其中field1=x1的记录。

How can I do this filtering on a Pandas dataframe? 如何在Pandas数据框上执行此过滤?

You need to check for tag2 in the list of field2 . 您需要在field2列表中检查tag2 Using .apply() , you can achieve this. 使用.apply() ,您可以实现此目的。

df[df.apply(lambda x: 'tag2' in x['field2'],axis=1)]

Output: 输出:

    field1  field2
0   x1      [tag1, tag2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 pandas dataframe 按作为列表的列的值过滤行 - pandas dataframe filter rows by values of column that is a list 在 pandas dataframe 中,如何根据列值过滤行,进行计算并将结果分配给新列? - In a pandas dataframe, how can I filter the rows based on a column value, do calculation and assign the result to a new column? 根据列列表值筛选 pandas dataframe - Filter pandas dataframe based on column list values 如何根据Python中列的行中列表中的值过滤数据帧? - How to filter a dataframe based on the values present in the list in the rows of a column in Python? 如何使用 python 或 pandas 根据包含字典列表的列过滤 DataFrame? - How do I use python or pandas to filter a DataFrame based on a column that consists of a list of dictionary? 如何根据字典列字段列表中的键值对过滤 DataFrame 行? - How do I filter DataFrame rows based on a key value pair from a list of dictionaries column field? 如何在 Pandas Dataframe 中获取行并转换为列的值? - How do I take rows in Pandas Dataframe and transform into values for a Column? 如何根据列值从 DataFrame 中 select 行? - How do I select rows from a DataFrame based on column values? 如何根据列值迭代地选择 pandas 中的行? - How do I iteratively select rows in pandas based on column values? 如何根据 pandas 中的列值合并附近的行? - How do I merge near rows based on column values in pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM