根据列中的一个用另一个数据框架替换数据框架中的值

时间:2020-08-27 20:48:25

标签: python pandas for-loop

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

p2 <- ggplot(df, aes(disp, mpg)) + theme_bw() +
  geom_point(data=df[which(df$n <= 150),],
             aes(size=n, color="Lower than 150"), fill='gray', shape=21) +
  geom_point(data=df[which(df$n > 150),],
             aes(fill=model, size=n), shape=21) +
  scale_color_manual(values='gray') +
  guides(
    fill=guide_legend(ncol=2, order=2, override.aes = list(size=4)),
    size=guide_legend(direction="horizontal", title.position="top", order=1),
    color=guide_legend(title=NULL, order=3, override.aes = list(size=4))
  )
p2

例如:

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

1 个答案:

答案 0 :(得分:0)

您是否尝试过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)