【问题标题】:Trying to make new column of values from second dataframe based on values in two other columns尝试根据其他两列中的值从第二个数据框中创建新的值列
【发布时间】:2022-01-27 03:18:05
【问题描述】:

我有两个数据框,df1 有与数据相关联的月份和年份列,df2 有月份(以数字表示)作为标题,年份作为索引值。

然后,我尝试使用与 df2 中的月/年对应的适当值填充 df1 中的新列。我尝试过 .loc 函数,但不确定它是要填充一整列还是一次只返回一个值。

df1

other data month year
xyz 12 1966
xyz 1 1997

df2

index 1 2 3 4 5 .... 12
1929 x y z x y .... z
1930 x y z x y .... z
... x y z x y .... z
1966 x y z x y .... z
1997 x y z x y .... z

我希望像这样根据 df2 中的值向 df1 添加一个新列:

other data month year df2_value
xyz 12 1966 z
xyz 1 1997 x

到目前为止,我一直在尝试这个:

df1['df2_value'] = df2.loc[df1['year'],df2['month']]

但我遇到了这个关键错误:

KeyError: "None of [Int64Index([12,  1,  2,  3,  2,  2,  3,  2,  4,  1,  1,  2,  3,  2,  1,  2,  2,\n
2,  2,  2, 12,  3,  1,  2, 12,  1,  2, 11,  3,  1,  2,  1,  3, 12,\n             
4,  3,  2,  1,  3,  2, 11, 12, 10, 12,  2,  4,  3,  1,  4,  1,  1,\n             
2,  3,  1,  2,  4,  2,  2,  2,  4,  2,  3, 12,  9, 12,  3,  2,  3,\n             
1,  2,  3, 11, 11,  4],\n           dtype='int64')] are in the [columns]"

我已将 df1 中的月份和年份列更改为对象类型而不是整数,但这并没有改变错误。这是我第一次尝试使用 .loc,所以可能会遗漏一些非常明显的东西,或者我可能需要使用完全不同的功能?

【问题讨论】:

    标签: python pandas dataframe .loc


    【解决方案1】:

    只需堆叠df2,重置索引并合并

    df1.merge(df2.stack().reset_index(),
              left_on=['year', 'month'],
              right_on=['index', 'level_1'])
    
    
      other data month  year index level_1  0
    0        xyz    12  1966  1966      12  z
    1        xyz     1  1997  1997       1  x
    

    【讨论】:

    • 谢谢!我对此很陌生,所以可能仍然缺少一些东西。现在我有一个数据框,其中包含所有正确的标题,例如您的示例,但数据框为空...我这样做了: df1 = df1.merge(df2.stack().reset_index(), left_on=['year', ' month'], right_on=['index', 'level_1']) 这是否意味着它们实际上并不匹配?
    • 它不适用于您在这个问题中的示例数据集还是您的真实数据?您可能需要检查合并字段 - 即 left_onright_on 值,以确保它们被正确格式化为整数或字符串。如果字符串确保没有多余的空格会阻止它们匹配。
    • 玩弄了这些类型,现在让它匹配,非常感谢!
    猜你喜欢
    • 2021-10-03
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2021-09-15
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多