Gre*_*reg 5 python dataframe pandas
如何在 python/pandas 中执行最小值的累积和?
下表中:
数据框
change in inventory inventory cumsum
2015-01-01 100 100 100
2015-01-02 -20 80 80
2015-01-03 -30 50 50
2015-01-04 -40 10 10
2015-01-05 -15 0 -5
2015-01-06 100 100 95
Run Code Online (Sandbox Code Playgroud)
实现此目的的一种方法是使用循环,但它会很混乱,并且可能有一种更有效的方法来做到这一点。
这是生成数据帧的代码:
import pandas as pd
df = pd.DataFrame.from_dict({'change in inventory': {'2015-01-01': 100,
'2015-01-02': -20,
'2015-01-03': -30,
'2015-01-04': -40,
'2015-01-05': -15,
'2015-01-06': 100},
'inventory': {'2015-01-01': 100,
'2015-01-02': 80,
'2015-01-03': 50,
'2015-01-04': 10,
'2015-01-05': 0,
'2015-01-06': 100}})
df['cumsum'] = df['change in inventory'].cumsum()
df
Run Code Online (Sandbox Code Playgroud)
如何在 python/pandas 中应用最小值的累积和来生成“库存”列中显示的值?
不幸的是,您可以使用循环:
lastvalue = 0
newcum = []
for row in df['change in inventory']:
thisvalue = row + lastvalue
if thisvalue < 0:
thisvalue = 0
newcum.append( thisvalue )
lastvalue = thisvalue
print pd.Series(newcum, index=df.index)
2015-01-01 100
2015-01-02 80
2015-01-03 50
2015-01-04 10
2015-01-05 0
2015-01-06 100
dtype: int64
Run Code Online (Sandbox Code Playgroud)