【发布时间】:2020-02-26 19:19:35
【问题描述】:
我有一个唯一随机整数列表和一个包含一列列表的数据框,如下所示:
>>> panel
[1, 10, 9, 5, 6]
>>> df
col1
0 [1, 5]
1 [2, 3, 4]
2 [9, 10, 6]
我想要的输出是panel 和数据框中每个单独列表之间的重叠长度:
>>> result
col1 res
0 [1, 5] 2
1 [2, 3, 4] 0
2 [9, 10, 6] 3
目前,我正在使用apply 函数,但我想知道是否有更快的方法,因为我需要创建很多面板并为每个面板循环执行此任务。
# My version right now
def cntOverlap(panel, series):
# Typically the lists inside df will be much shorter than panel,
# so I think the fastest way would be converting the panel into a set
# and loop through the lists within the dataframe
return sum(1 if x in panel for x in series)
#return len(np.setxor1d(list(panel), series))
#return len(panel.difference(series))
for i, panel in enumerate(list_of_panels):
panel = set(panel)
df[f"panel_{i}"] = df["col1"].apply(lambda x: cntOverlap(panel, x))
【问题讨论】:
标签: python pandas numpy intersection set-intersection