我有一个包含列的数据框-
Product Price in AUD Price in BTC Price in USD Date
A 1450.22 0.120 NaN 2019-08-15
B NaN NaN 550 2019-09-12
C NaN 0.18 1500 2019-09-02
D NaN NaN 1244 2019-09-10
我需要将所有备用价格(比特币价格和美元价格)转换为Price in AUD
为空的Price in AUD
。如果同时给出了两个替代价格(例如C),我想使用Price in BTC
转换为AUD,无论哪个可用。
我该怎么做?由于比特币和美元的价格每天都在波动,我是否可以使用API或Python库呢?我想使用Date
列来获取该日期的确切的AUD转换值。有没有人做过类似的事情,可以为此提供帮助吗?
答案 0 :(得分:1)
您可以使用forex-python软件包:
import pandas as pd
import datetime
from forex_python.converter import CurrencyRates
from forex_python.bitcoin import BtcConverter
data = [('A', 1450.22 , 0.120 , None , '2019-08-15')
,('B', None , None , 550 , '2019-09-12')
,('C', None , 0.18 , 1500 , '2019-09-02')
,('D', None , None , 1244 , '2019-09-10')]
colNames = ['Product', 'Price in AUD', 'Price in BTC', 'Price in USD', 'Date']
df = pd.DataFrame(data, columns=colNames)
c = CurrencyRates()
b = BtcConverter()
def convertBtcToAUD(row):
if pd.isna(row['Price in AUD']):
date = datetime.datetime.strptime(row['Date'], '%Y-%m-%d')
aud = b.convert_btc_to_cur_on(row['Price in BTC'], 'AUD', date )
else:
aud = row['Price in AUD']
return aud
def convertUSDToAUD(row):
if pd.isna(row['Price in AUD']):
date = datetime.datetime.strptime(row['Date'], '%Y-%m-%d')
aud = c.convert('USD', 'AUD', row['Price in USD'], date )
else:
aud = row['Price in AUD']
return aud
df['Price in AUD'] = df.apply(convertBtcToAUD, axis=1)
df['Price in AUD'] = df.apply(convertUSDToAUD, axis=1)
输出:
Product Price in AUD Price in BTC Price in USD Date
0 A 1450.220000 0.12 NaN 2019-08-15
1 B 799.840372 NaN 550.0 2019-09-12
2 C 2783.197980 0.18 1500.0 2019-09-02
3 D 1814.504710 NaN 1244.0 2019-09-10
P.S .:请记住,stackoverflow不是代码编写服务。我只是提供了一个答案,因为我对该问题感兴趣。