繁体   English   中英

Pandas:设置 dataframe 的一列的值,条件是另一个 dataframe 的另一列

[英]Pandas: set the value of one column of a dataframe with condition on another column of another dataframe

我有两个数据框 df1 和 df2,每列有两列:

df1                                            df2
c1 c2                                          c2 c3

我想为 df1 创建一个新列 c3,它将是:

  • 当 df1.c2 = df2.c2 时,等于 df2 的 c3 列
  • 其他 NaN

这基本上就是 vlookup function 在 Excel 中所做的事情。

到目前为止,我已经尝试过:

df1["c3"] = np.nan

for i in df1.c2.unique():
    for j in df2.c2.unique():
        if i == j:
            df1.loc(df1.c2 == i, "c3") = df2.loc(df2.c2 == j, "c3")
        else:
            pass
        

但是当我打印结果df1时, c3保持不变......我通过在循环中分别打印它们来检查我的df1.locdf2.loc ,它们都瞄准了正确的值......

谁能帮我解决这个问题?

PS:为了进一步了解,我正在尝试将 pygal 国家代码与相应的国家/地区相关联,以便在世界 map 中将它们 plot。

df1 = my dataset

df1.c1 = relavant data

df1.c2 = country name

df1.c3 = country code

df2 = pygal country code table

df2.c2 = country name

df2.c3 = country code
        

NumPy np.where()这样的东西:

df1['c3'] = np.where(df1['c2'] == df2['c2'], df2['c3'], np.nan)

有点像 Excel 中的if()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM