如何在数据帧内进行减法

2024-05-09 10:53:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于数据帧中的算术的问题。请注意,除了“holdings”之外,我的数据框中的以下每一列都是基于另一列的

这是我的数据帧的一个缩短版本

'holdings' & 'cash' & 'total'
0.0           10000.0   10000.0
0.0           10000.0   10000.0
1000          9000.0    10000.0
1500          10000.0   11500.0
2000          10000.0   12000.0

initial_cap = 10000.0

但我的问题是。。。我第一次持有现金时,现金的计算是正确的,其中现金10000.0-持有1000.0=9000.0

我需要现金保持在9000.0,直到我的持股再次回到0.0 这是我的计算

换言之,如何计算现金,使其保持在9000.0,直到持有量回到0.0

这是我想要的样子

'holdings' & 'cash' & 'total'
0.0           10000.0   10000.0
0.0           10000.0   10000.0
1000          9000.0    10000.0
1500          9000.0   10500.0
2000          9000.0   11000.0

现金=初始资本-持有


Tags: 数据版本cash算术initialtotal资本cap
1条回答
网友
1楼 · 发布于 2024-05-09 10:53:06

所以我试着换个说法:你从初始资本开始10和一个给定的持股序列{0, 0, 1, 1.5, 2},然后想创建一个cashvariable,它是10,只要cash0。一旦cash在一个初始阶段增加x,你就希望现金10 - x,直到现金再次等于0。你知道吗

如果这是正确的,这就是我将要做的(我仍然不清楚总体和所有这一切的逻辑,但这是你在最后补充的,所以我重点关注这个)。你知道吗

另外,提供代码来创建您的示例被认为是很好的

df = pd.DataFrame([0, 1, 2, 2, 0, 2, 3, 3], columns=['holdings'])
x = 10
# triggers are when cash is supposed to be zero
triggers = df['holdings'] == 0
# inits are when holdings change for the first time
inits = df.index[triggers].values + 1
df['cash'] = 0
for i in inits:
    df['cash'][i:] = x - df['holdings'][i]
df['cash'][triggers] = 0
df
Out[339]: 
   holdings  cash
0         0     0
1         1     9
2         2     9
3         2     9
4         0     0
5         2     8
6         3     8
7         3     8

相关问题 更多 >