2017-06-30 51 views
2

我有貨幣價值的數據幀英鎊日期:熊貓 - 選擇基於單元格的值列

    USD  EUR  JPY  CAD  CNH 
date               
2017-06-29 0.770151 0.879765 0.006857 0.591919 0.113538 
2017-06-28 0.773038 0.878451 0.006892 0.592764 0.113687 
2017-06-27 0.781594 0.885069 0.006952 0.593128 0.114724 
2017-06-26 0.785476 0.879456 0.007045 0.593763 0.114849 

和含有值英鎊轉換另一個數據框:

  price  date currency 
0 21404.00000 2017-06-26  USD 
3 21445.00000 2017-06-26  USD 
4  1.27213 2017-06-26  USD 
5  111.67500 2017-06-26  JPY 
6  1.27205 2017-06-26  EUR 
8  111.65500 2017-06-26  JPY 
9  111.65500 2017-06-26  JPY 

我的目標是將貨幣數據框「加入」數值,導致新的rate列:

  price  date currency  rate 
0 21404.00000 2017-06-26  USD 0.785476 
3 21445.00000 2017-06-26  USD 0.785476 
4  1.27213 2017-06-27  USD 0.781594 
5  111.67500 2017-06-27  JPY 0.006952 
6  1.27205 2017-06-28  EUR 0.885069 
8  111.65500 2017-06-28  JPY 0.006892 
9  111.65500 2017-06-29  JPY 0.006857 

我對任何使用apply或其他類型的基於行的迭代的方法都不感興趣。相反,我會尋找一種操縱前兩個數據幀的向量化方式來獲得第三個數據幀。

回答

3

使用lookup找到你的利率和assign在新柱砸

df.assign(rate=currencies.lookup(df.date, df.currency)) 

     price  date currency  rate 
0 21404.00000 2017-06-26  USD 0.785476 
3 21445.00000 2017-06-26  USD 0.785476 
4  1.27213 2017-06-27  USD 0.781594 
5 111.67500 2017-06-27  JPY 0.006952 
6  1.27205 2017-06-28  EUR 0.878451 
8 111.65500 2017-06-28  JPY 0.006892 
9 111.65500 2017-06-29  JPY 0.006857 
-1

好吧,這有點亂。但是你可以使用一個應用功能相匹配的日期,然後得到正確的一列,例如

currency_data = [['2017-06-29',0.770151,0.879765,0.006857,0.591919,0.113538], 
       ['2017-06-28',0.773038,0.878451,0.006892,0.592764,0.113687]] 

currencies = pd.DataFrame(currency_data, 
          columns=['date', 'USD', 'EUR', 'JPY', 'CAD', 'CNH']) 

trans_data = [[21404.00000, '2017-06-29', 'USD'], 
       [21445.00000, '2017-06-28', 'JPY']] 

trans = pd.DataFrame(trans_data, columns=['amount', 'date', 'currency']) 

def map_currency(row): 
    return currencies[currencies['date'] == row['date']][row['currency']].iloc[0] 

rates = trans.apply(map_currency, axis=1) 
rates.name = 'rate' 
pd.concat([trans, rates], axis=1) 

enter image description here