【发布时间】:2019-06-10 08:51:35
【问题描述】:
我有一个pandas dataframe,它在 split_categories 列中包含一个列表:
df.head()
album_id categories split_categories
0 66562 480.494 [480, 494]
1 114582 128 [128]
2 4846 5 [5]
3 1709 9 [9]
4 59239 105.104 [105, 104]
我想选择特定列表 [480, 9, 104] 中至少一个类别所在的所有行。
预期输出:
album_id categories split_categories
0 66562 480.494 [480, 494]
3 1709 9 [9]
4 59239 105.104 [105, 104]
我设法使用apply:
def match_categories(row):
selected_categories = [480, 9, 104]
result = [int(i) for i in row['split_categories'] if i in selected_categories]
return result
df['matched_categories'] = df.apply(match_categories, axis=1)
但是这段代码在生产环境中运行,这种方式耗时太长(我为包含列表的多个列运行它)
有没有办法运行类似的东西:
df[~(df['split_categories'].anyvalue.isin([480, 9, 104]))]
谢谢
【问题讨论】:
-
df['split_categories']中列表的最大大小是多少,例如总是 1 或 2 项?
标签: python pandas python-2.7