【问题标题】:Pandas update column A in dataframe1 where dataframe1 column2 matches dataframe2 column [duplicate]熊猫更新dataframe1中的A列,其中dataframe1 column2匹配dataframe2列[重复]
【发布时间】:2021-12-03 07:18:30
【问题描述】:

我有 2 个数据框:

df1 = pd.DataFrame(
[
  (73, 15, 'update1', 1, 'foo'),
  (63, 64, 'update2', 2, 'bar'),
  (56, 72, 'update3', 3, 'foo'),
],
columns=['A', 'B', 'C', 'D', 'E'],
)

df2 = pd.DataFrame(
[
  (73, 15, 'new1', 2, 'foo'),
  (63, 64, 'new2', 3, 'bar'),
  (56, 72, 'new3', 1, 'foo'),
],
columns=['A', 'B', 'C', 'D', 'E'],
)

我正在寻找一种方法将这两个数据帧加入 D 列,然后更新 df1 的 C 列,以匹配 df2 中 C 列的值。

最终结果:

df1 = pd.DataFrame(
[
  (73, 15, 'new3', 1, 'foo'),
  (63, 64, 'new1', 2, 'bar'),
  (56, 72, 'new2', 3, 'foo'),
],
columns=['A', 'B', 'C', 'D', 'E'],
)

感谢任何帮助。

到目前为止我尝试了什么?

运行 for 循环并通过查找 df2 中 c 列的对应值来更新 df1 中的值。

【问题讨论】:

    标签: python python-3.x pandas dataframe data-science


    【解决方案1】:

    一种方法是使用map:

    df1['C'] = df1.D.map(df2.set_index('D').C)
    
    df1
        A   B     C  D    E
    0  73  15  new3  1  foo
    1  63  64  new1  2  bar
    2  56  72  new2  3  foo
    

    df2.set_index('D').Cdf2 中返回您需要的从DC 的映射:

    df2.set_index('D').C
    
    D
    2    new1
    3    new2
    1    new3
    Name: C, dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2019-02-18
      • 2019-12-29
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多