【问题标题】:Replacing values in data frame with another data frame based on one of the columns基于其中一列将数据框中的值替换为另一个数据框
【发布时间】:2020-08-27 20:48:25
【问题描述】:

我有两个数据框,一个包含一些信息,一个较短的数据框包含我想对第一个进行的一些修改。我已经尝试过类似于下面写的内容。

for x in df['var']:
    if x in df2['var']:
         df['var2'] == df2['var2']

例如:

---> df
        num_legs  num_wings  num_specimen_seen
falcon         2          2                 10
dog            4          0                  2
spider         8          0                  1
fish           0          0                  8

---> df1
        num_legs  num_wings  num_specimen_seen
dog            4          0                  5
spider         8          0                  9

---> output
        num_legs  num_wings  num_specimen_seen
falcon         2          2                 10
dog            4          0                  5
spider         8          0                  9
fish           0          0                  8

【问题讨论】:

标签: python pandas for-loop


【解决方案1】:

你试过df.update()

df.update(df1)



        num_legs  num_wings  num_specimen_seen
falcon       2.0        2.0               10.0
dog          4.0        0.0                5.0
spider       8.0        0.0                9.0
fish         0.0        0.0                8.0

替代方案

import numpy as np
df[df.index.isin(df1.index)]=np.nan
df1.combine_first(df)

工作原理

#Find shared index between the two dataframes which are in df.

df[df.index.isin(df1.index)]

#Make them NaN


df[df.index.isin(df1.index)]=np.nan

#Use [.combine_first][1] to fill them

df1.combine_first(df)

【讨论】:

  • @anona 让我知道你的情况。很高兴为您提供进一步的帮助
  • 这有帮助吗?
  • 感谢您的帮助。我试了一下,但我发现它正在将观察结果添加到列表中,而不是更新它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
相关资源
最近更新 更多