首页 > 解决方案 > 使用列表理解的子集熊猫数据框

问题描述

我有一个数据框 A,它有一个名为 text 的列,它是长字符串。我想保留具有字符串列表“author_id”中的任何字符串的“A”行。

A data frame:
Dialogue Index  author_id   text
10190       0    573660    How is that even possible?
10190       1    23442     @573660 I do apologize. 
10190       2    573661    @AAA do you still have the program for free checked bags? 

author_id list:
[573660, 573678, 5736987]

因此,由于 573660 在 author_id 列表中并且在 A 的文本列中,我的预期结果是只保留数据框 A 的第二行:

 Dialogue   Index   author_id   text
 10190        1       23442     @573660 I do apologize. 

我能想到的最天真的解决方法是:

 new_A=pd.DataFrame()   
 for id in author_id:
      new_A.append(A[A['text'].str.contains(id, na=False)]

但这需要很长时间。

所以我想出了这个解决方案:

[id in text for id in author_id for text in df['text'] ]

但这不适用于对数据框进行子集化,因为我为每个作者 ID 的 df['text'] 中的所有字符串都获得了真假值。

所以我在数据框中创建了一个新列,它是 Dialogue 和 Index 的组合,所以我可以在列表理解中返回它,但它给出了一个我不知道如何解释的错误。

A["DialogueIndex"]= df["Dialogue"].map(str) + df["Index"]

newA = [did for did in df["DialogueIndex"]  for id in author_id if df['text'].str.contains(id)  ]

error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

请帮忙。

标签: pythonpandaslist-comprehension

解决方案


只需使用str.contains来查看是否text包含您指定列表中的任何作者(通过将所有作者加入|

import pandas as pd
df = pd.DataFrame({
    'Dialogue': [10190, 10190, 10190],
    'Index': [0,1,2],
    'author_id': [573660,23442,573661],
    'text': ['How is that even possible?', 
             '@573660 I do apologize.',
            '@AAA do you still have the program for free checked bags?']
})
author_id_list = [573660, 573678, 5736987]

df.text.str.contains('|'.join(list(map(str, author_id_list))))
#0    False
#1     True
#2    False
#Name: text, dtype: bool

然后你可以掩盖原来的DataFrame

df[df.text.str.contains('|'.join(list(map(str, author_id_list))))]
#   Dialogue  Index  author_id                     text
#1     10190      1      23442  @573660 I do apologize.

如果您author_id_list已经是字符串,那么您可以摆脱list(map(...))并加入原始列表。


推荐阅读