使用来自另一个数据帧中匹配索引的值设置数据帧列 [英] Set dataframe column using values from matching indices in another dataframe

查看:52
本文介绍了使用来自另一个数据帧中匹配索引的值设置数据帧列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用保存在 DF2 中 col2 匹配索引处的值来设置 DF1 的 col2 中的值:

I would like to set values in col2 of DF1 using the value held at the matching index of col2 in DF2:

DF1:

         col1    col2
index
    0       a
    1       b
    2       c
    3       d
    4       e
    5       f

DF2:

         col1    col2
index
    2       a      x
    3       d      y
    5       f      z

DF1':

         col1    col2
index
    0       a     NaN
    1       b     NaN
    2       c       x
    3       d       y
    4       e     NaN
    5       f       z

如果我只是尝试设置 DF1['col2'] = DF2['col2'] 那么 col2 作为 DF1' 中的所有 NaN 值出现 - 我认为这是因为索引不同.但是,当我尝试使用 map() 执行以下操作时:

If I just try and set DF1['col2'] = DF2['col2'] then col2 comes out as all NaN values in DF1' - I take it this is because the indices are different. However when I try and use map() to do something like:

DF1.index.to_series().map(DF2['col2'])

然后我仍然得到相同的 NaN 列,但我认为它会将值映射到索引匹配的位置...

then I still get the same NaN column, but I thought it would map the values over where the index matches...

我没有得到什么?

推荐答案

您需要 joinassign:

df = df1.join(df2['col2'])
print (df)
      col1 col2
index          
0        a  NaN
1        b  NaN
2        c    x
3        d    y
4        e  NaN
5        f    z

或者:

df1 = df1.assign(col2=df2['col2']) 
#same like
#df1['col2'] = df2['col2']
print (df1)

      col1 col2
index          
0        a  NaN
1        b  NaN
2        c    x
3        d    y
4        e  NaN
5        f    z

如果不匹配且所有值都是 NaN,请检查索引在两个 df 中是否具有相同的 dtype:

If no match and all values are NaNs check if indices have same dtype in both df:

print (df1.index.dtype)
print (df2.index.dtype)

如果不是,则使用 astype:

If not, then use astype:

df1.index = df1.index.astype(int)
df2.index = df2.index.astype(int)

<小时>

糟糕的解决方案(检查索引 2):


Bad solution (check index 2):

df = df2.combine_first(df1)
print (df)
      col1 col2
index          
0        a  NaN
1        b  NaN
2        a    x
3        d    y
4        e  NaN
5        f    z

这篇关于使用来自另一个数据帧中匹配索引的值设置数据帧列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆