温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Pandas pickup and merge data from n-dataframes into one dataframe
dataframe lookup merge pandas python

python - pandas 拾取并将n个数据帧中的数据合并到一个数据帧中

发布于 2020-04-21 14:10:50

我已经在该主题上查找了另一个类似的问答,但是我无法弄清楚我的问题,因此,我很高兴获得任何提示。当我要收集数据时,我在字典中存储了三个数据帧,在另一个数据帧中存储了另一个数据帧。

import numpy as np
import pandas as pd

df1= pd.DataFrame({'tenor':['1w', '1m', '3m', '2y'],
                   'rate':[2.40, 2.51, 2.66, 2.92],
                   'end_date':['14022020', '09022020', '07052020', '07022022']})

df2= pd.DataFrame({'tenor':['3x6', '6x9', '9x12'],
                   'rate':[2.95, 3.06, 3.98],
                   'end_date':['07082020', '09112020', '08022021']})

df3= pd.DataFrame({'tenor':['2y', '3y', '4y'],
                   'rate':[1.80, 1.81, 1.84],
                   'end_date':['08022022', '07022023', '07022024']})


rates = {'ois':df1, 'fra':df2, 'irs':df3}


dfA= pd.DataFrame({'label':['ois', 'ois', 'fra', 'fra', 'irs', 'irs', 'irs'],
                   'tenor':['1w', '1m', '3x6', '9x12', '2y', '3y', '4y']})

我想通过从匹配['tenor']的核心响应数据帧(通过字典映射)中获取值,在dfA中添加另一个columne ['rates']。因此,预期结果将是这样的:

Out[]: 
  label tenor  rate
0   ois    1w  2.40
1   ois    1m  2.51
2   fra   3x6  2.95
3   fra  9x12  3.98
4   irs    2y  1.80
5   irs    3y  1.81
6   irs    4y  1.84

我知道我可以使用以下行在数据框中获取特定数据(例如):

rates['ois'].loc[rates['ois']['tenor']=='1w', 'rate']
Out[]: 
0    2.4
Name: rate, dtype: float64

因此,我尝试使用以下代码将其嵌入apply()函数:

dfA['rate'] = dfA.apply(lambda x: rates[x['label']][rates[x['label']]['tenor']==x['tenor']]['rate'], axis=1)

但不幸的是它返回:

Out[]: 
  label tenor  rate
0   ois    1w  2.40
1   ois    1m   NaN
2   fra   3x6  2.95
3   fra  9x12   NaN
4   irs    2y  1.80
5   irs    3y   NaN
6   irs    4y   NaN

我不明白为什么有些汇率是NaN。我在这里想念什么?请帮忙。

查看更多

提问者
halny
被浏览
14
Michel Guimarães 2020-02-06 04:23

我不知道这是否对您来说是一个很周到的解决方案,但是我想在下面进行说明:

  1. 在另一个DataFrame中连接df:

    dfAux = pd.concat([df1, df2, df3])

  2. 使用左侧的dfA进行合并:

    dfA = pd.merge(dfA, dfAux, how = 'left', on = ['tenor']).drop(['end_date'], axis = 1)