筛选 pandas 数据帧行(如果数据帧内列表中的任何值位于另一个列表中)



我有一个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]))]

谢谢

您可以将每个列表转换为集合,获取交集并转换为布尔值:

L = [480, 9, 104]
mask = np.array([bool(set(map(int, x)) & set(L))  for x in df['split_categories']])

或者将list column转换为DataFrame,投射为浮点并与isin进行比较:

df1 = pd.DataFrame(df['split_categories'].values.tolist(), index=df.index)
mask = df1.astype(float).isin(L).any(axis=1)

df = df[mask]
print (df)
  album_id categories split_categories
0    66562    480.494       [480, 494]
3     1709          9              [9]
4    59239    105.104       [105, 104]

您可以展开内部列表,并检查内部列表中的any项是否包含在[480, 9, 104]中:

l = [480, 9, 104]
df[df.categories.str.split('.', expand=True).isin(map(str,l)).any(axis=1)]
   album_id  categories split_categories
0     66562     480.494        [480,494]
3      1709       9.000              [9]
4     59239     105.104        [105,104]

避免一系列列表

您可以拆分为多个数字序列,然后使用矢量化布尔运算。使用逐行操作的 Python 级循环通常效率较低

df = pd.DataFrame({'album_id': [66562, 114582, 4846, 1709, 59239],
                   'categories': ['480.494', '128', '5', '9', '105.104']})
split = df['categories'].str.split('.', expand=True).add_prefix('split_').astype(float)
df = df.join(split)
print(df)
#    album_id categories  split_0  split_1
# 0     66562    480.494    480.0    494.0
# 1    114582        128    128.0      NaN
# 2      4846          5      5.0      NaN
# 3      1709          9      9.0      NaN
# 4     59239    105.104    105.0    104.0
L = [480, 9, 104]
res = df[df.filter(regex='^split_').isin(L).any(1)]
print(res)
#    album_id categories  split_0  split_1
# 0     66562    480.494    480.0    494.0
# 3      1709          9      9.0      NaN
# 4     59239    105.104    105.0    104.0

另一种方法:

my_list = [480, 9, 104]
pat = r'({})'.format('|'.join(str(i) for i in my_list))
#'(480|9|104)' <-- This is how the pat looks like
df.loc[df.split_categories.astype(str).str.extract(pat, expand=False).dropna().index]

或:

pat = '|'.join(r"b{}b".format(x) for x in my_list)
df[df.split_categories.astype(str).str.contains(pat,na=False)]
    album_id    categories  split_categories
0   66562       480.494     [480, 494]
3   1709        9.000       [9]
4   59239       105.104     [105, 104]

这将适用于split_categories列和categories列。

使用:

print(df[~(df['split_categories'].isin([480, 9, 104])).any()])

输出:

  album_id categories split_categories
0    66562    480.494       [480, 494]
3     1709          9              [9]
4    59239    105.104       [105, 104]

最新更新