【问题标题】:Pandas: set the value of one column of a dataframe with condition on another column of another dataframe熊猫:在另一个数据框的另一列上设置数据框的一列的值
【发布时间】:2021-07-15 04:03:41
【问题描述】:

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

df1                                            df2
c1 c2                                          c2 c3

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

  • 当 df1.c2 = df2.c2 时,等于 df2 的 c3 列
  • 否则为 NaN

这基本上就是 vlookup 函数在 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 国家代码与相应的国家/地区相关联,以便将它们绘制在世界地图中。

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
        

【问题讨论】:

  • 您能展示一下您的数据框是什么样子以及您想要实现的目标吗?

标签: python pandas dataframe


【解决方案1】:

类似这样的 NumPy np.where():

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

有点像 Excel 中的 if()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-20
    • 2023-04-03
    • 2019-04-22
    • 2022-01-23
    • 2022-01-23
    • 2016-08-09
    • 2017-04-14
    • 2017-12-08
    相关资源
    最近更新 更多