当其列值至少包含给定列表中的一个元素时,使用映射获取新 Dataframe 的列表理解

List Comprehension with Mapping to Get a New Dataframe When Its Column Value Contains At Least One Element in A Given List

我有一个数据框 df。我最终想要一个新的数据框,df 中的 'question' 列包含列表 answer.

中的一个元素
answer = ['a','b','c','d','e']
df = pd.DataFrame({'question': ['a,b', 'b,c', 'z', 'f,e', 'x', 'd']})

>>> df
  question
0      a,b
1      b,c
2        z
3      f,e
4        x
5        d

我希望所需的输出数据帧为:

>>> new_df
  question
0      a,b
1      b,c
3      f,e
5        d

这就是我到目前为止所简化的内容。

for y in answer:
    new_df = df[df['question'].map(lambda x: y in x)]
我想到了这样的东西并得到了以下错误:
new_df = df[df['question'].map(lambda x: y in x for y in answer)]

TypeError: 'generator' object is not callable

如何使用列表理解在一行代码中得到满足条件的新数据框?

使用df.isin而不是列表理解:

df = pd.DataFrame({'question': ['a,b', 'b,c', 'z', 'f,e', 'x', 'd']})
>>> df['question'].str.split(',') \
                  .apply(lambda x: len(set(x).intersection(answer)) != 0)
0     True
1     True
2    False
3     True
4    False
5     True
Name: question, dtype: bool

新数据框:

new_df = df[df['question'].str.split(',') \
                          .apply(lambda x: len(set(x).intersection(answer)) != 0)]
>>> new_df
  question
0      a,b
1      b,c
3      f,e
5        d

您可以将 Series.str.contains, Pandas.concat and DataFreame.sort_index 与理解列表一起使用:

df_result = pd.concat([df[df['question'].str.contains(a)] for a in answer]).drop_duplicates().sort_index()

但是,如果你问我上面的代码不可读,那么我让你上面的代码没有列表理解来更好地理解:

list_dfs = []
for a in answer:
  # df_match will be a tiny dataframe with the matching.
  # For instance, In the first iteration will be:
  #      question
  # 0      a,b  
  df_match = df[df['question'].str.contains(a)]
  list_dfs.append(df_match)

df_result = pd.concat(list_dfs).drop_duplicates().sort_index()
print(df_result)

对于两个版本,输出是相同的:

    question
0   a,b
1   b,c
3   f,e
5   d