【问题标题】:Python Pandas - complete/fill dataframe based on the another one [duplicate]Python Pandas - 基于另一个完成/填充数据框[重复]
【发布时间】:2021-01-17 09:36:35
【问题描述】:

我正在与最佳优化(无循环等)解决方案作斗争,以在第二个基础上完成数据帧。

例如我有主 df:

      owner  toy   id_toy
0     Simon  Car   11
1     Tommy  Lego  12
2     Kate   Lego  7
3     Kate   Duck  7
4     Kate   Car   11

第二个df:

      toy  id_toy  weight  color
0     Car  11      12.00   red
1     Lego 12      5.00    white
2     Duck 7       8.00    yellow

我想根据第二个df填充主df,它应该如下所示:

      owner  toy   id_toy  weight  color
0     Simon  Car   11      12.00   red
1     Tommy  Lego  12      5.00    white
2     Kate   Lego  7       5.00    white
3     Kate   Duck  7       8.00    yellow
4     Kate   Car   11      12.00   red

是否可以使用一些 pandas 函数在“几行”内完成?

【问题讨论】:

  • pd.merge(df1,df2.drop('toy',1),on='id_toy',how='left')

标签: python pandas dataframe fill


【解决方案1】:

使用 merge() 函数作为:

df1.merge(df2,how='inner',by='id_toy')

【讨论】:

  • 因为有一个 ID 列,您应该将其用作任何类型合并的来源。
猜你喜欢
  • 2017-04-03
  • 2018-09-22
  • 1970-01-01
  • 2020-11-26
  • 2021-10-27
  • 2020-04-26
  • 2021-12-16
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多