python - 忽略索引的两个数据帧的快速减法(Python)

标签 python performance pandas dataframe

如何以最快的方式减去忽略索引的 2 个数据帧。

例如,我想减去:

d1=
      x1
0 -3.141593
0 -3.141593
0 -3.141593
1 -2.443461
1 -2.443461

来自

d2 = 
      x2
1 -2.443461
2 -1.745329
3 -1.047198
4 -0.349066
2 0.349066

我尝试过的:

我可以这样做,例如:

dsub = d1.reset_index(drop=True) - d2.reset_index(drop=True)

但是,我想以最有效的方式进行减法。我一直在四处寻找答案,但我只看到了不考虑速度的解决方案。

我该如何实现?


编辑 根据一些答案,以下是在我的机器上运行的一些时间:

对于较小的数据框:

方法 1(a 和 b):

a: d1.reset_index(drop=True) - d2.reset_index(drop=True)
b: d1.reset_index(drop=True).sub(d2.reset_index(drop=True))
~1024.91 usec/pass

方法二:

d1 - d2.values
~784.79 usec/pass

方法三:

pd.DataFrame(d1.values - d2.values, d1.index, ['x1-x2'])
~653.82 usec/pass

对于非常大的数据帧,请参阅下面@MaxU 的回答。

最佳答案

你可以这样做:

d1 - d2.values

或:

d1.x1 - d2.x2.values

演示:

In [172]: d1 - d2.values
Out[172]:
         x1
0 -0.698132
0 -1.396264
0 -2.094395
1 -2.094395
1 -2.792527

In [173]: d1.x1 - d2.x2.values
Out[173]:
0   -0.698132
0   -1.396264
0   -2.094395
1   -2.094395
1   -2.792527
Name: x1, dtype: float64

更大 DF 的时机:

In [180]: d1 = pd.concat([d1] * 10**5, ignore_index=True)

In [181]: d2 = pd.concat([d2] * 10**5, ignore_index=True)

In [182]: d1.shape
Out[182]: (500000, 1)

In [183]: %timeit pd.DataFrame(d1.values - d2.values, d1.index, ['x1-x2'])
100 loops, best of 3: 4.07 ms per loop

In [184]: %timeit d1 - d2.values
100 loops, best of 3: 3.99 ms per loop

In [185]: d1 = pd.concat([d1] * 10, ignore_index=True)

In [186]: d2 = pd.concat([d2] * 10, ignore_index=True)

In [187]: d1.shape
Out[187]: (5000000, 1)

In [188]: %timeit pd.DataFrame(d1.values - d2.values, d1.index, ['x1-x2'])
10 loops, best of 3: 19.9 ms per loop

In [189]: %timeit d1 - d2.values
100 loops, best of 3: 14 ms per loop

In [190]: %timeit d1.reset_index(drop=True) - d2.reset_index(drop=True)
1 loop, best of 3: 242 ms per loop

In [191]: %timeit d1.reset_index(drop=True).sub(d2.reset_index(drop=True))
1 loop, best of 3: 242 ms per loop

关于python - 忽略索引的两个数据帧的快速减法(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40476064/

相关文章:

performance - 每秒请求数和响应时间之间的相关性?

python - 在 pandas DataFrame 中使用多个条件会导致 ValueError

python - 如何获取 Pandas 中 groupby 对象中每个项目的索引?

python - OpenCV 不会在 PyCharm 中导入

python - 为什么 requests.get() 不返回? requests.get() 使用的默认超时是多少?

Python - 新手 : Why this simple if-elif (replication of the C case block) always produces the same result?

android - Android 后台任务的流媒体视频播放性能问题

performance - IndexedDB 访问速度和效率

python - csv 格式的数据,用双引号括起来

python - 如何使用 Python 和 Networkx 在图中找到循环关系?