Python / pandas:从两个数据框中查找匹配的值并返回第三个值

时间:2019-12-18 14:58:22

标签: python pandas dataframe

我有两个形状完全不同的数据帧(df1,df2):df1:(64,6); df2:(564,9)。 df1包含一列(df1.objectdesc),该列的值(字符串)也可以在df2(df2.objdescription)的列中找到。由于两个数据框的形状不同,因此我必须使用.isin()来获取匹配的值。然后,我想从恰好匹配并添加到df1的那些行中,从df2的另一列(df2.idname)中获取第三个值。

示例数据集:

df1

      Content    objectdesc    TS_id
0     sdrgs      1_OG.Raum45   55
1     sdfg       2_OG.Raum23   34
2     psdfg      GG.Raum12     78
3     sdfg       1_OG.Raum98   67

df2:

      Numb_val    object_count     objdescription    min   idname
0     463         9876             1_OG_Raum76       1     wq19
1     251         8324             2_OG.Raum34       9     zt45
2     456         1257             1_OG.Raum45       4     bh34
3     356         1357             2_OG.Raum23       3     if32
4     246         3452             GG.Raum12         5     lu76
5     345         8553             1_OG.Raum98       8     pr61

预期输出:

      Content    objectdesc    TS_id    idname
0     sdrgs      1_OG.Raum45   55       bh34
1     sdfg       2_OG.Raum23   34       if32
2     psdfg      GG.Raum12     78       lu76
3     sdfg       1_OG.Raum98   67       pr61

到目前为止,这是我的代码:

def get_id(x, y):
    for values in x,y:
        if x['objectdesc'].isin(y['objdescription']).any() == True:
            return y['idname']

df1['idname'] = get_id(df1, df2) 

不幸的是,这仅提供了从索引0开始的df2['idname']的值,而没有真正给我匹配行中的值。

感谢您的帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以将两者合并。

from io import StringIO

import pandas as pd

df_1_str = \
    '''
    Content    objectdesc    TS_id
    sdrgs      1_OG.Raum45   55
    sdfg       2_OG.Raum23   34
    psdfg      GG.Raum12     78
    sdfg       1_OG.Raum98   67
    '''

df_2_str = \
    '''
    Numb_val    object_count     objdescription    min   idname
    463         9876             1_OG_Raum76       1     wq19
    251         8324             2_OG.Raum34       9     zt45
    456         1257             1_OG.Raum45       4     bh34
    356         1357             2_OG.Raum23       3     if32
    246         3452             GG.Raum12         5     lu76
    345         8553             1_OG.Raum98       8     pr61
    '''

df_1 = pd.read_csv(StringIO(df_1_str), header=0, delim_whitespace=True)

df_2 = pd.read_csv(StringIO(df_2_str), header=0, delim_whitespace=True)

df_3 = df_1.merge(df_2[['objdescription', 'idname']], left_on='objectdesc',
                  right_on='objdescription').drop('objdescription', axis='columns')

df_3的内容:

    Content    objectdesc      TS_id  idname
--  ---------  ------------  -------  --------
 0  sdrgs      1_OG.Raum45        55  bh34
 1  sdfg       2_OG.Raum23        34  if32
 2  psdfg      GG.Raum12          78  lu76
 3  sdfg       1_OG.Raum98        67  pr61

答案 1 :(得分:0)

可以尝试以下方法:

df1.merge(df2, left_on='objectdesc', right_on='objdescription')[['Content', 'objectdesc', 'TS_id', 'idname']]

参考:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html