【问题标题】:Python: Create some sort of cumsum between two columnsPython:在两列之间创建某种 cumsum
【发布时间】:2019-11-22 20:44:38
【问题描述】:

我试图弄清楚如何使用多列获得某种运行总计,但我什至不知道从哪里开始。我以前使用过 cumsum,但只用于一列,这不起作用。

我有这张桌子:

      Index       A         B       C    
        1        10        12      20    
        2        10        14      20   
        3        10         6      20    

我正在尝试构建如下所示的表:

      Index       A         B       C       D
        1        10        12      20      10
        2        10        14      20      18
        3        10         6      20      24

D 的公式如下: D2 = ( D1 - B1 ) + C1

D1 = A 列

关于如何做到这一点的任何想法?我对此完全没有想法。

【问题讨论】:

  • 这能回答你的问题吗? Cumulative Sum using 2 columns
  • 额,怎么10-14+12=-16?
  • 2020 年 1 月 2 日的新库存显示为 -12,对吧?
  • 哦,是的,很好。所以输出应该是[10, -12, 8] ?

标签: python pandas


【解决方案1】:

这应该可行:


df.loc[0, 'New_Inventory'] = df.loc[0, 'Inventory']   
for i in range(1, len(df)):
    df.loc[i, 'New_Inventory'] = df.loc[i-1, 'Inventory'] - df.loc[i-1, 'Booked'] - abs(df.loc[i-1, 'New_Inventory'])
df.New_Inventory = df.New_Inventory.astype(int)  

df
#      Index  Inventory  Booked  New_Inventory
#0  1/1/2020         10      12             10
#1  1/2/2020         10      14            -12
#2  1/3/2020         10       6            -16

【讨论】:

  • 这在很大程度上解决了我的问题,经过如下所示的一些修改,我让它按照我需要的 i in range(2, len(df)+1) 工作:跨度>
【解决方案2】:

你可以通过shift得到你的答案,参考答案here

import pandas as pd
raw_data = {'Index':      ['1/1/2020', '1/2/2020', '1/3/2020', '1/4/2020', '1/5/2020'],
        'Inventory':     [10, 10, 10, 10, 10],
         'Booked':       [12,14,6,3,5] }

df = pd.DataFrame(raw_data)
df['New_Inventory'] = 10 # need to initialize
df['New_Inventory'] = df['Inventory'] - df['Booked'].shift(1) - df['New_Inventory'].shift(1)
df

您请求的输出似乎错误。以上New_Inventory 的计算是所要求的。

【讨论】:

  • NewInventory(i) 取决于 NewInvetory(i-1)。您必须扩展公式以创建通用公式
猜你喜欢
  • 2018-07-24
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多