python - 使用列表理解的子集熊猫数据框
问题描述
我有一个数据框 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().
请帮忙。
解决方案
只需使用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(...))
并加入原始列表。
推荐阅读
- android - Html.fromHtml() 无法解码锚属性的字体颜色
- html - 嵌套引导网格填充问题
- reactjs - 是否可以等待调度完成
- windows - Windows 进程激活服务 (WAS) 将无法启动
- c# - 转换 DateTime.Now.Ticks.ToString("x"); 回到人类可读的时间戳
- typescript - 如何通过在 Typescript 中提供其名称作为参数来获取枚举值
- python - 视图 user.views.profile 没有返回 HttpResponse 对象。它返回 None 而不是
- php - 声纳扫描仪所有文件
- css - 在reactjs中最大化div宽度
- matlab - 合并来自多个 .log 文件的数据并读取它们,而无需在 MATLAB 中创建新的 .txt 文件