【问题标题】:Set dataframe column using values from matching indices in another dataframe使用来自另一个数据框中匹配索引的值设置数据框列
【发布时间】:2021-07-19 07:33:10
【问题描述】:

我想使用DF2col2 的匹配索引中保存的值来设置DF1col2 中的值:

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

DF3:

         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 会作为DF3 中的所有NaN 值出现——我认为这是因为索引不同。但是,当我尝试使用 map() 执行以下操作时:

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

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

我没有得到什么?

【问题讨论】:

  • 你试试 df1[["col2"]] = df2[["col2"]]

标签: python pandas


【解决方案1】:

您需要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

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

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

如果不是,则使用 astype:

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

错误的解决方案(检查索引 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

【讨论】:

    【解决方案2】:

    您可以在根据索引组合时简单地连接

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2020-09-11
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多