gpt4 book ai didi

python - 使用 pandas 对多个映射货币列进行操作

转载 作者:行者123 更新时间:2023-12-01 00:23:32 25 4
gpt4 key购买 nike

我有两个数据帧,即 df1 和 df2。我想对 df2 中的“Amount_Dollar”列执行操作。基本上在 df1 中,我有历史货币数据,并且我想根据 df2 中给定的货币和 Amount_Dollar 执行日期操作,以计算 df2 中 New_Amount_Dollar 列的值。

对于“货币”== [AUD、BWP],我们需要将 Amount_Dollar 乘以相应日期的相应货币值。

如果 df1 中没有任何货币,则不要对“Amount_Dollar”执行任何操作(意味着采用相同的值)

对于其他可用货币,我们需要将 Amount_Dollar 除以相应日期的相应货币值(value)。

例如,在 df2 中,我的第一种货币为澳元,日期 = '01-01-2019',因此我想计算 New_Amount_Dollar 值,使得

New_Amount_Dollar = Amount_Dollar*来自 df1 的澳元值,即 New_Amount_Dollar = 19298*98 = 1891204

另一个例子,在 df2 中,我有第三种货币作为 Date = '03-01-2019 的 COP,所以我想计算 New_Amount_Dollar 值,使得

New_Amount_Dollar = Amount_Dollar/df1 的 COP 值,即 New_Amount_Dollar = 5000/0.043 = 116279.06

import pandas as pd
data1 = {'Date':['01-01-2019', '02-01-2019', '03-01-2019',
'04-01-2019','05-01-2019'],
'AUD':[98, 98.5, 99, 99.5, 97],
'BWP':[30, 31, 33, 32, 31],
'CAD':[0.02, 0.0192, 0.0196, 0.0196, 0.0192],
'BND':[0.99, 0.952, 0.970, 0.980, 0.970],
'COP':[0.05, 0.047, 0.043, 0.047, 0.045]}
df1 = pd.DataFrame(data1)

data2 = {'Date':['01-01-2019', '02-01-2019', '03-01-2019', '04-01-2019','05-01-2019'],
'Currency':['AUD','AUD','COP','NZD','BND'],
'Amount_Dollar':[19298, 19210, 5000, 200, 2300],
'New_Amount_Dollar':[0,0,0,0,0]
}
df2 = pd.DataFrame(data2)

df1

         Date    AUD  BWP     CAD    BND    COP
0 01-01-2019 98.0 30 0.0200 0.990 0.050
1 03-01-2019 98.5 31 0.0192 0.952 0.047
2 04-01-2019 99.0 33 0.0196 0.970 0.043
3 05-01-2019 99.5 32 0.0196 0.980 0.047
4 06-01-2019 97.0 31 0.0192 0.970 0.045
5 09-01-2019 100.0 20 0.2000 0.230 0.023

df2

         Date Currency  Amount_Dollar  New_Amount_Dollar
0 01-01-2019 AUD 19298 0
1 02-01-2019 AUD 19210 0
2 03-01-2019 COP 5000 0
3 04-01-2019 NZD 200 0
4 07-01-2019 BND 2300 0

预期结果

         Date Currency  Amount_Dollar  New_Amount_Dollar
0 01-01-2019 AUD 19298 1891204.00
1 02-01-2019 AUD 19210 1892185.00
2 03-01-2019 COP 5000 116279.06
3 04-01-2019 NZD 200 200.00
4 05-01-2019 BND 2300 2371.13

最佳答案

首先,unstack df1得到一列所有FX,稍后将用于连接:

df1.set_index('Date', inplace=True)
df1 = pd.DataFrame(df1.unstack(), columns = ['FX'])

然后加入 df2。为 CAD 和 BWP 添加 mask ,取 CAD/BWP 的倒数。然后进行列操作以获得新的金额。

df2 = df2.merge(df1, left_on = ['Currency', 'Date'], right_index = True, how = 'left').fillna(1)
df2['mask'] = df2['Currency'].isin(['AUD', 'BWP'])
df2.loc[df2['mask'], 'FX'] = 1/df2.loc[df2['mask'], 'FX']
df2['New_Amount_Dollar'] = df2['Amount_Dollar'] / df2['FX']

关于python - 使用 pandas 对多个映射货币列进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58790545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com