【问题标题】:Appending to next row the result of math operation between three columns将三列之间的数学运算结果附加到下一行
【发布时间】:2020-06-17 02:37:51
【问题描述】:

所以,我有以下 Pandas DataFrame,其中第三列(比率)中的所有值都相同:

import pandas as pd 

df = pd.DataFrame([[2, 10, 0.5], 
                   [float('NaN'), 10, 0.5], 
                   [float('NaN'), 5, 0.5]], columns=['Col1', 'Col2', 'Ratio'])
╔══════╦══════╦═══════╗
║ Col1 ║ Col2 ║ Ratio ║
╠══════╬══════╬═══════╣
║ 2    ║   10 ║ 0.5   ║
║ NaN  ║   10 ║ 0.5   ║
║ NaN  ║    5 ║ 0.5   ║
╚══════╩══════╩═══════╝

我想知道是否有办法将 Col1 * Ratio 相乘,然后将该乘积的输出添加到 Col2 并使用 pandas 提供的函数将该值附加到下一行 Col1。

输出示例:

╔══════╦══════╦═══════╗
║ Col1 ║ Col2 ║ Ratio ║
╠══════╬══════╬═══════╣
║ 2    ║   10 ║ 0.5   ║
║ 11   ║   10 ║ 0.5   ║
║ 15.5 ║    5 ║ 0.5   ║
╚══════╩══════╩═══════╝

【问题讨论】:

  • 更好地使用for循环
  • @YOBEN_S 这就是我想避免的,如果可能的话。
  • 我不确定你是否可以,因为在你的操作中每一行都取决于前一行的结果......所以它们必须按顺序执行。 (也许你可以使用apply 或其他东西来避免显式循环,但这只是在引擎盖下循环......)
  • 各行的比例不同?
  • @QuangHoang 不,所有行的比率保持不变。

标签: python pandas


【解决方案1】:

如果性能很重要,我认为numba 是在这里使用循环的方式:

from numba import jit

@jit(nopython=True)
def f(a, b, c):
    for i in range(1, a.shape[0]):
        a[i] = a[i-1] * c[i-1] + b[i-1]
    return a

df['Col1'] = f(df['Col1'].to_numpy(), df['Col2'].to_numpy(), df['Ratio'].to_numpy())
print (df)
   Col1  Col2  Ratio
0   2.0    10    0.5
1  11.0    10    0.5
2  15.5     5    0.5

【讨论】:

  • 那么,似乎没有 pandas 内置函数来实现问题的目标,我已将此标记为正确答案,因为至少它专注于性能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
相关资源
最近更新 更多