带熊猫的vlookup-如何用另一个数据框中的值填充空列

时间:2020-07-22 18:31:04

标签: pandas dataframe vlookup

这对我来说是熊猫的一个新概念。我对Excel中的vlookup非常熟悉,所以这是我想做的事情:

df1=                      df2=
FUR  Total   otherT          FUR   Total
123    3     no value        123    8
345   -2     no value        345    3
234    6     no value        234   -1

所以我要做的就是将df2的合计列放在df1中名为OtherT的空列中。 “无值”仅表示该字段为空白。

我尝试使用合并

pd.merge(df1, df2, how = 'left', on = 'FUR')

我也尝试过使用连接

df1.join(df2, on = 'FUR', how  = 'left')

1 个答案:

答案 0 :(得分:0)

我知道这是一个老问题,但我今天遇到了同样的问题。 我所做的是使用 apply 来模拟 Excel VLOOKUP 函数,例如:

df1=                      df2=
FUR  Total   otherT          FUR   Total
123    3     no value        123    8
345   -2     no value        345    3
234    6     no value        234   -1

df['otherT'] = df[df.otherT == 'no value']. \
               FUR.apply(lambda x: df2[df2.FUR = x] \                                                         
                        ['Total'].values[0] if len (df2[df2.FUR = x] \                                                         
                        .values) > 0 else 'no value')

仅在 VLOOKUP 行上应用 'no value'

df[df.otherT == 'no value']

而这部分是为了避免什么都没有发现的错误。

if len (df2[df2.FUR = x].values) > 0 else 'no value'

作为 excel VLOOKUP 此函数将获取第一个结果。