我有一个带有4列的熊猫数据框 res : 帐户,货币,余额LCY,余额FCY
i还有一个词典 rates ,其中包含所有不同的货币汇率(主要货币名称:值汇率为字符串) 我需要将货币不是EUR的帐户的“余额LCY”更改为平衡FCY /汇率。
我尝试运行:
res['Balance LCY'].loc[res['Currency'] != 'EUR'] = res['Balance FCY'] / float(rates[res['Currency']])
但是我遇到了错误:
TypeError: 'Series' objects are mutable, thus they cannot be hashed
任何帮助表示赞赏。
问题似乎是在拉动特定单元格的值 货币列,以在外部字典中执行查找。
我自己解决了这个问题,方法是将字典变成一个数据框,将其与原始res数据框连接起来,然后进行计算。
解决方案代码:
erates = pd.DataFrame(list(rates.items()), columns=['Currency', 'Rate'])
res = pd.merge(res, erates, how='left', on='Currency')
res.loc[res['Currency'] != 'EUR', 'Balance LCY'] = res['Balance FCY'] / res['Rate']
样本数据 RES:
Account,Currency,Balance LCY,Balance FCY
123,EUR,-299183.94,0
124,EUR,-28578532,0
125,EUR,0,0
126,CAD,0,0
127,PLN,0,-2646970
128,ZAR,0,-5026915
129,DKK,0,-2862948.8
130,CHF,0,-343557.9
131,USD,0,-71672.87
132,CAD,0,84295.63
133,SGD,0,-269976.9
134,TRY,0,-494451.56
135,NZD,0,-256601.95
136,JPY,0,0
费率:
rates= {
"CAD": 1.432,
"HKD": 8.4117,
"ISK": 138.3,
"PHP": 54.955,
"DKK": 7.4702,
"HUF": 337.1,
"CZK": 25.061,
"AUD": 1.6363,
"RON": 4.804,
"SEK": 10.569,
"IDR": 14867.58,
"INR": 77.754,
"BRL": 4.755,
"RUB": 69.548,
"HRK": 7.449,
"JPY": 120.96,
"THB": 34.164,
"CHF": 1.061,
"SGD": 1.5131,
"PLN": 4.2835,
"BGN": 1.9558,
"TRY": 6.6131,
"CNY": 7.5945,
"NOK": 10.0873,
"NZD": 1.7104,
"ZAR": 16.2965,
"USD": 1.0801,
"MXN": 20.5183,
"ILS": 3.6985,
"GBP": 0.8351,
"KRW": 1309.45,
"MYR": 4.5294
}
答案 0 :(得分:0)
有一个简单的设计解决方案-您应始终将基础货币添加到汇率等于1的字典中。
在您的情况下:
rates["EUR"]=1
erates = pd.DataFrame(list(rates.items()), columns=['Currency', 'Rate'])
res = pd.merge(res, erates, how='left', on='Currency')
res["Balance LCY"]=res["Balance FCY"].div(res["Rate"])
输出:
Account Currency Balance LCY Balance FCY Rate
0 123 EUR 0.000000 0.00 1.0000
1 124 EUR 0.000000 0.00 1.0000
2 125 EUR 0.000000 0.00 1.0000
3 126 CAD 0.000000 0.00 1.4320
4 127 PLN -617945.605229 -2646970.00 4.2835
5 128 ZAR -308465.928267 -5026915.00 16.2965
6 129 DKK -383249.283821 -2862948.80 7.4702
7 130 CHF -323805.749293 -343557.90 1.0610
8 131 USD -66357.624294 -71672.87 1.0801
9 132 CAD 58865.663408 84295.63 1.4320
10 133 SGD -178426.343269 -269976.90 1.5131
11 134 TRY -74768.498889 -494451.56 6.6131
12 135 NZD -150024.526427 -256601.95 1.7104
13 136 JPY 0.000000 0.00 120.9600