【问题标题】:faster column-multiply in dataframe数据框中更快的列乘法
【发布时间】:2021-01-02 13:37:03
【问题描述】:

我有一个熊猫数据框 A,它有 2 列 x 和 y。我想像B = A['x'] * A['y'] 一样将它们相乘。有没有更快的方法来做到这一点? A['a'].mul(A['y']) 会更快吗?

【问题讨论】:

  • 在文档中,它说 mul 相当于 * 所以我怀疑它会更快。 Equivalent to dataframe * other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rmul.

标签: python dataframe multiplication


【解决方案1】:

要检查哪个更快,您可以检查每种情况所需的时间: 在 Ipython 或 Jupiter 中将是:

%%timeit
    d['a'] * d['b']

对于这样的数据框:

a = np.arange(0,10000)
b = np.ones(10000)

d = pd.DataFrame(np.vstack([a,b]).T, columns=["a","b"])

得到你的乘法:

1- 在熊猫中

d['a'] * d['b']
81.2 µs ± 977 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

2 - 在 numpy.避免 pandas 开销

d['a'].values * d['b'].values
9.21 µs ± 41.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

...如果您非常担心速度,请使用 numpy。利用 pandas 的优良特性,让您可以通过 values 特性访问数组。

【讨论】:

    【解决方案2】:

    Numpy 更快,如果你的列很长,你可以使用 np.arrays

    import numpy as np
    
    B=np.array(A.x)*np.array(A.y)
    

    在我的 PC 上对具有 55K 行的数据帧进行快速测试,将时间从 0.78 秒(您的原始方法)减少到 0.54 秒(上述方法)

    【讨论】:

      【解决方案3】:

      我只能同意@IoaTzimas 的评论,Numpy 更快。因此,您最好将要相乘的 Dataframe 列转换为 Numpy arrays 并使用它们。

      如果您有数组中的初始数据,您可以将它们转换为 numpy 数组并使用它。

      如果您将数据保存在 Dataframe 中并且需要事先将其提取出来,您可以执行以下操作:

      from numpy import multiply as npMultiply
      
      # get the values from the Dataframe to arrays
      x_array = A['x'].values
      y_array = A['y'].values
      
      B = npMultiply(x_array, y_array)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        相关资源
        最近更新 更多