[英]Replacing values in data frame with another data frame based on one of the columns
I have two dataframes, one that contains some information and a shorter dataframe that contains some amendments I want to make to the first.我有两个数据框,一个包含一些信息,一个更短的数据框包含我想对第一个进行的一些修改。 I have tried something similar to that written below.
我尝试过类似于下面写的东西。
for x in df['var']:
if x in df2['var']:
df['var2'] == df2['var2']
For example:例如:
---> 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
Have you tried df.update()
你试过
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
Alternative选择
import numpy as np
df[df.index.isin(df1.index)]=np.nan
df1.combine_first(df)
How it works这个怎么运作
#Find shared index between the two dataframes which are in 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.