数据帧中具有相关性的条件累积和

2024-05-29 05:00:58 发布

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

我试图计算一系列金融交易的两个累计金额。共有4种交易类型,每种类型都有交易金额: 存款 W-撤回 G增益 L-损失

数据帧是这样创建的

import pandas as pd
import numpy as np

data = { 'Type': ['D', 'D', 'W', 'D', 'G', 'G', 'G', 'L', 'W', 'G', 'W', 'G', 'L' ],
         'Amount': [10, 10, -5, 10, 5, 5, 5, -5, -10, 10, -25, 25, -30]
       }
df = pd.DataFrame(data, columns = ['Type', 'Amount'])

使用cumsum()可以很容易地计算流动资金,它基本上包括所有交易

df['Capital'] = df['Amount'].cumsum()

我要计算的另一个实体是本金,它表示输入帐户的金额。这只考虑D和W类型的事务。我可以在这里使用以下方法进行简单筛选:

df['Principal'] = df.apply(lambda row : row['Amount'] if (row['Type'] == 'W' or row['Type'] == 'D') else 0, axis=1).cumsum()

然而,这有一个问题。当存在收益和提款时,提款需要在影响本金之前从收益中提款。上面的输出在下面的结果中有错误(第8行和第10行):

    Type    Amount  Capital Principal
0   D       10      10      10
1   D       10      20      20
2   W       -5      15      15
3   D       10      25      25
4   G       5       30      25
5   G       5       35      25
6   G       5       40      25
7   L       -5      35      25
8   W       -10     25      15   <- should stays at 25
9   G       10      35      15   <- now wrong because of above
10  W       -25     10      -10  <- error escalades
11  G       25      35      -10
12  L       -30     5       -10

我可以通过做下面的事情得到想要的结果,但是看起来有点难看。 想知道是否有更简单或快捷的方法。我想这是金融界常见的计算方法

df['Principal'] = np.nan
currentPrincipal = 0
for index, row in df.iterrows():
    if (row['Type'] == 'D'):
        #row['Principal'] = currentPrincipal + row['Amount']
        df.loc[index, 'Principal'] = currentPrincipal + row['Amount']
    elif (row['Type'] == 'W' and row['Capital'] <= currentPrincipal):
        #row['Principal'] = row['Capital']
        df.loc[index, 'Principal'] = row['Capital']
    else:
        df.loc[index, 'Principal'] = currentPrincipal
        
    currentPrincipal = df.loc[index, 'Principal']

我没有成功地尝试使用apply,因为我们依赖于Principal之前的结果,需要继续。 正确结果:

    Type    Amount  Capital Principal
0   D       10      10      10
1   D       10      20      20
2   W       -5      15      15
3   D       10      25      25
4   G       5       30      25
5   G       5       35      25
6   G       5       40      25
7   L       -5      35      25
8   W       -10     25      25
9   G       10      35      25
10  W       -25     10      10
11  G       25      35      10
12  L       -30     5       10

Tags: importprincipal类型dfindexastype交易
1条回答
网友
1楼 · 发布于 2024-05-29 05:00:58

你可以做:

# calculate cumulative withdrawals
w = df['Amount'].where(df['Type'].eq('W')).cumsum()

# calculate cumulative deposits
d = df['Amount'].where(df['Type'].eq('D'), 0).cumsum()

# calculate cumulative gain & loss
g = df['Amount'].where(df['Type'].isin(['G', 'L']), 0).cumsum()

# calculate principal = deposit + net_withdrawal(if any)
df['Principal'] =  d + (g + w).where(lambda x: x < 0).ffill().fillna(0)

结果:

   Type  Amount  Capital  Principal
0     D      10       10       10.0
1     D      10       20       20.0
2     W      -5       15       15.0
3     D      10       25       25.0
4     G       5       30       25.0
5     G       5       35       25.0
6     G       5       40       25.0
7     L      -5       35       25.0
8     W     -10       25       25.0
9     G      10       35       25.0
10    W     -25       10       10.0
11    G      25       35       10.0
12    L     -30        5       10.0

相关问题 更多 >

    热门问题