【问题标题】:Merging two different-dimension data frames based on column ID using panda使用panda基于列ID合并两个不同维度的数据框
【发布时间】:2019-05-07 09:47:27
【问题描述】:

我有两个 panda data.frames

df1

**Title** **ID**  
  Intro     A
   P1       B
   P2       C
  Concl     D

df2

**body** **likes** **ID**
  Hello      1       A
  Stack      2       A
 Overflow    3       A
  How's      4       B
   It        5       C
  Going      6       C
    ?        7       D

我想根据 ID 合并数据框,得到结果数据框:

desired_df

**Title**  **ID**  **body**  **likes**
  Intro      A       Hello       1
  Intro      A       Stack       2
  Intro      A      Overflow     3
   P1        B       How's       4
   P2        C        It         5
   P2        C       Going       6
 Conclu      D        ?          7

列的顺序无关紧要(如果 df2 列在 df1 之前先排序)。

这可能吗?我希望 df1 的 Title 列中的值重复,如所需数据框中所示

【问题讨论】:

标签: python


【解决方案1】:

这个怎么样:

print(pandas.merge(df1, df2, on='ID', how='inner'))

我无法从您的示例中判断您是要执行内部联接还是外部联接。但是您可以使用how 参数来指定它。

文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html#pandas.merge

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2021-07-28
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多