通过匹配变量将一个 pandas 数据帧的值添加到另一个数据帧

Adding value from one pandas dataframe to another dataframe by matching a variable

假设我有一个 pandas 数据框 df 有 2 列

           c1            c2
    0      v1            b1
    1      v2            b2
    2      v3            b3
    3      v4            b4
    4      v5            b5

第二个数据框,df2 包含 c1、c2 和其他一些列。

   c1 c2 c3  c4
0  "" b5 500 3
1  "" b2 420 7
2  "" b1 380 5
3  "" b2 470 9
4  "" b3 290 2

我的目标是将 df2 中 c1 的空值替换为 df 中的空值,对应于 c2 中的值,因此 df2 中 c1 的前五个值应为 v5、v2、v1、v2 和v3分别。最好的方法是什么?

您可能正在寻找这样的东西:

import pandas as pd
import numpy as np
# remove the c1 column from df2
df2.drop("c1", axis=1, inplace=True)
# merge the 2 dataframes and get the c1 values corresponding to c2
newdf = df.merge(df2, on="c2")

如果您确实在列中有缺失值(即 NA 和一些存在值的行,则解决方案会有所不同)

一种简单的方法是使用基于相似列的 pandas 合并。

df2.drop('c1', axis=1, inplace=True)
main_df = pd.merge(df2, df, on="c2", how="left")
df2['c1'] = main_df['c1']
df2.columns = ['c1','c2','c3','c4']