【问题标题】:Pandas creating a new column by merging two dataframes and matching rows [duplicate]Pandas 通过合并两个数据框和匹配行来创建新列 [重复]
【发布时间】:2021-09-30 13:46:32
【问题描述】:

我有两个数据框,其中一个匹配列 [ID]。

DF 1

ID     VAR
1      442
1      429
1      58
2      928
2      8493
3      093
3      809
3      913
4      133
4      490

DF2

ID       CODE
1        10foo
2        20bar
3        30foo
4        40bar

我正在尝试合并这些数据框,以便得到如下内容:

DF 3

ID     VAR      CODE
1      442      10foo
1      429      10foo
1      58       10foo
2      928      20bar
2      8493     20bar
3      093      30foo
3      809      30foo
3      913      30foo
4      133      40bar
4      490      40bar

我已经用DF3 = DF1.merge(DF2, on='ID', how='inner', right_index=True) 尝试过这个 这确实有效,但最终会复制大量值,由于某种原因使行数增加了一倍以上。真的不知道为什么会这样。我需要 DF3 中的行数与 DF1 相同

感谢您的帮助。

【问题讨论】:

  • 首先,通过validate='m:1' 告诉我们结果
  • 您的示例与您的代码不一致。为什么是right_index=True 而不是left_index=True。您的 2 个数据框似乎具有相同的格式?而这种情况下,你不能使用on='ID',因为onx_index是互斥的。
  • 这是pd.Series.map 的典型用例。你可以试试df1['CODE'] = df1['ID'].map(df2.set_index('ID')['CODE'])

标签: python pandas dataframe merge


【解决方案1】:

要保持与 DF1 相同的行数,您需要左合并:

df1.merge(df2, on='ID', how='left')

【讨论】:

    【解决方案2】:

    我们可以试试这个:

    >>> df = pd.merge(df1,
    ...               df2,
    ...               how='left',
    ...               left_on=['ID'],
    ...               right_on=['ID'])              
    >>> df
       ID   VAR     CODE
    0   1   442     10foo
    1   1   429     10foo
    2   1   58      10foo
    3   2   928     20bar
    4   2   8493    20bar
    5   3   93      30foo
    6   3   809     30foo
    7   3   913     30foo
    8   4   133     40bar
    9   4   490     40bar
    

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 2019-07-15
      • 2021-11-12
      • 2018-09-04
      • 1970-01-01
      • 2020-12-21
      • 2017-05-23
      • 2018-09-17
      • 2020-01-31
      相关资源
      最近更新 更多