3 回答
TA贡献1829条经验 获得超6个赞
使用这个解决方案,只是简化,因为排序已经交换:
df['new'] = df.values.dot(1 << np.arange(df.shape[-1]))
print (df)
v1 v2 v3 v4 new
0 0 0 0 0 0
1 1 0 1 1 13
2 0 0 1 1 12
3 0 1 0 1 10
4 1 1 1 1 15
1000行和 4 列的性能:
np.random.seed(2019)
N= 1000
df = pd.DataFrame(np.random.choice([0,1], size=(N, 4)))
df.columns = [f'v{x+1}' for x in df.columns]
In [60]: %%timeit
...: df['new'] = df.values.dot(1 << np.arange(df.shape[-1]))
113 µs ± 1.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
尤卡解决方案:
In [65]: %%timeit
...: variables = ['v1', 'v2', 'v3', 'v4']
...: df['added'] = df['v1']
...: for ind, var in enumerate(variables[1:]) :
...: df['added'] = df['added'] + [x<<ind for x in df[var]]
...:
1.82 ms ± 16.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
原解决方案:
In [66]: %%timeit
...: variables = ['v1', 'v2', 'v3', 'v4']
...: df['added'] = df['v1']
...: for ind, var in enumerate(variables[1:]) :
...: df['added'] = df['added'] + df[var].apply(lambda x : x << ind )
...:
3.14 ms ± 8.52 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
TA贡献2036条经验 获得超8个赞
在回答您关于更有效替代方案的问题时,我发现列表理解确实对您有所帮助:
variables = ['v1', 'v2', 'v3', 'v4']
df['added'] = df['v1']
for ind, var in enumerate(variables[1:]) :
%timeit df['added'] = df['added'] + [x<<ind for x in df[var]]
308 µs ± 22.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
322 µs ± 19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
316 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
所以 315 µs 与:
variables = ['v1', 'v2', 'v3', 'v4']
df['added'] = df['v1']
for ind, var in enumerate(variables[1:]) :
%timeit df['added'] = df['added'] + df[var].apply(lambda x : x << ind )
500 µs ± 38.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
503 µs ± 32.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
481 µs ± 32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
作为免责声明,我不同意总和的价值,但这是一个不同的话题:)
添加回答
举报