【问题标题】:How can i speed up a np.linsolve method for a pandas Dataframe?如何加快 pandas Dataframe 的 np.linsolve 方法?
【发布时间】:2021-04-11 14:50:29
【问题描述】:

我目前有一个 Datafame,如下所示:

Account1 Account2 Name Surname
150 18 Peter Müller
130 1200 Hans Zimmer
150 18 Franz Joseph
106 1200 Joe Trump
150 18 Christoph Walz
170 1200 Anne Will
150 138 Lucenci Hart
1056 1200 Defig Iano

我现在正试图找到一个值m,它会为函数带来完美的解决方案:

 for x in range(len(data)):
            Account1 = data.loc[x, 'Account1']
            Account2 = data.loc[x, 'Account2']
            m = 1

            a = np.array([[-Account2 - m * Account1]])
            b = np.array([[-Account2 * Account1 + (Account1 ** 2) * m]])
            solution = ((np.linalg.solve(a, b)))
            data.loc[x, "m_solution"] = solution[0]

这样它就会返回:

m_solution
-117.857
104.586
-117.857
88.793
-117.857
127.810
-6.25
67.404

这确实工作得很好,但是对于超过 50000 行的 df,它需要很长时间。

有没有办法使用 lambda 之类的东西来优化这个问题,或者可能已经有 pandas 函数可以立即解决这样的问题?

【问题讨论】:

  • 我是否正确推断 ab 都是 (1,1) 数组?所以第一个数字就是(-18*150+(150**2)*1)/(-18-1*150)?为什么用linsolve做简单的除法?
  • 尝试设置Account1 = data['Account1']等,一次对所有行进行上述计算。我认为您不需要迭代行,也不需要使用linsolve。这只是根据两个系列的值进行的简单计算。

标签: python pandas numpy lambda


【解决方案1】:

正如我评论的那样:

In [80]: Account1 = df['Account1']
    ...: Account2 = df['Account2']
    ...: m = 1
    ...: a = -Account2 - m * Account1
    ...: b = -Account2 * Account1 + (Account1 ** 2) * m
    ...: solution = b/a
    ...: df["m_solution"] = solution
In [81]: df
Out[81]: 
   Account1  Account2  m_solution
0       150        18 -117.857143
1       130      1200  104.586466
2       150        18 -117.857143
3       106      1200   88.793262
4       150        18 -117.857143
5       170      1200  127.810219
6       150       138   -6.250000
7      1056      1200   67.404255

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2018-12-18
    • 2021-09-30
    • 2017-12-11
    • 2016-01-14
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多