我有一個包含 2 列的數據框 - 一個元組和一個列表:
df = t l
(1,2) [1,2,3,4,5,6]
(0,5) [1,4,9]
(0,4) [9,11]
我想添加一個新列“l 中有多少元素在 t 的範圍內。例如,這裡 if 將是:
df =counter t l
2 (1,2) [1,2,3,4,5,6]
2 (0,5) [1,4,9]
0 (0,4) [9,11]
這樣做的最佳方法是什麼?
使用帶有生成器和的列表理解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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句