将列表推导与生成器和sum一起使用:
df['counter'] = [sum(a <= i <= b for i in y) for (a, b), y in df[['t','l']].to_numpy()]
set.intersection 的更快解决方案是:
df['counter'] = [len(set(range(a, b+1)).intersection(y))
for (a, b), y in df[['t','l']].to_numpy()]
print (df)
t l counter
0 (1, 2) [1, 2, 3, 4, 5, 6] 2
1 (0, 5) [1, 4, 9] 2
2 (0, 4) [9, 11] 0
性能在测试数据中:
#30k rows
df = pd.concat([df] * 10000, ignore_index=True)
In [67]: %timeit [sum(a <= i <= b for i in y) for (a, b), y in df[['t','l']].to_numpy()]
65.3 ms ± 1.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [68]: %timeit [len(set(range(a, b+1)).intersection(y)) for (a, b), y in df[['t','l']].to_numpy()]
60.7 ms ± 520 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)