2017-03-22 31 views
0

我有如下熊貓數據幀:蟒大熊貓:訪問日期時間系列進行貨幣換算

>>> df.head() 
      Date   From  To  Currency Net 
TransID 
4569219  2015-02-21 Calzada  Michael MXN   2396.0 
5630763  2013-08-18 Juan  Edgar  USD   155.56 
4698552  2013-08-17 David  Jessica MXN   1965.23 
5706840  2013-08-11 Edgar  Luis  MXN   923.22 
7522850  2011-08-11 Jonathan Juan  USD   58.23 

Date系列是dtype: datetime64[ns]Net一個是dtype: float64

我想根據給定日期的匯率將任何墨西哥比索(MXN)金額轉換爲美元。

要做到這一點,我使用的forex_python庫,例如:

>>> from forex_python.converter import CurrencyRates 
... from datetime import datetime 
... 
... c = CurrencyRates() 
... amount = 1000 
... date = datetime(2013,02,21) 
... print c.convert('MXN','USD', amount, date) 
78.344 

該功能可將1000 MXN和USD返回量。現在我想將它應用於我的數據框,但是我得到了不同類型的錯誤。首先,我曾嘗試:

from forex_python.converter import CurrencyRates 
from datetime import datetime 

c = CurrencyRates() 
df.loc[df['Currency'].str.contains('MXN'), 'Net'] = c.convert('MXN', 'USD', df['Net'], df['Dates']) 

,但我得到:

AttributeError: 'Series' object has no attribute 'strftime' 

這裏尋找錯誤後,我嘗試使用dt訪問的另一種方式:

from forex_python.converter import CurrencyRates 
from datetime import datetime 

c = CurrencyRates() 
df.loc[df['Currency'].str.contains('MXN'), 'Net'] = c.convert('MXN', 'USD', df['Net'], datetime(df['Date'].dt.year, df['Date'].dt.month, df['Date'].dt.day)) 

這一次我得到另一個錯誤:

TypeError: cannot convert the series to <type 'int'> 

我應該強調,如果我不使用日期參數(但我得到今天的匯率),它工作正常。即:

df.loc[df['Currency'].str.contains('MXN'), 'Net'] = c.convert('MXN', 'USD', df['Net']) 
df['Currency'] = 'USD' 

我愛我的最終結果是:

>>> df.head() 
      Date   From  To  Currency Net 
TransID 
4569219  2015-02-21 Calzada  Michael USD   158.68 
5630763  2013-08-18 Juan  Edgar  USD   155.56 
4698552  2013-08-17 David  Jessica USD   154.40 
5706840  2013-08-11 Edgar  Luis  USD   923.22 
7522850  2011-08-11 Jonathan Juan  USD   72.53 

它接縫就像我無法從Date系列中提取相應的日期在我c.convert()功能使用。我不知道如何在不提取我的信息和使用列表的情況下解決這個問題,我真的不想這麼做。

任何想法?

感謝您的幫助。

+0

您是否與FOREX費率掛鉤? https://www.oanda.com/currency/converter是否是一個選項?注意:它提供了略有不同的歷史匯率 – MaxU

回答

1

這是一個很好的使用案例apply,它可以通過axis=1遍歷所有行。

df['Date'] = pd.to_datetime(df.Date) 
df['Net'] = df.apply(lambda x: x.Net if x.Currency == 'USD' else 
           c.convert('MXN', 'USD', x.Net, x.Date), axis=1) 
df['Currency'] = 'USD' 

       Date  From  To Currency   Net 
TransID             
4569219 2015-02-21 Calzada Michael  USD 159.638292 
5630763 2013-08-18  Juan Edgar  USD 155.560000 
4698552 2013-08-17  David Jessica  USD 152.944025 
5706840 2013-08-11  Edgar  Luis  USD 73.240889 
7522850 2011-08-11 Jonathan  Juan  USD 58.230000 
+0

完美!非常感謝 :) ! – Mike