【问题标题】:Merging pandas dataframes based on lists of paired indices基于配对索引列表合并熊猫数据框
【发布时间】:2022-09-29 00:21:44
【问题描述】:

我有两个数据框,df1 和 df2,以及一组相当复杂的逻辑语句,我必须将它们作为单独的函数运行才能合并它们。该函数为df1 中的行和df2 中的行返回一对索引,现在看起来像

matches = [[1,2,7,14], [1,2,7,14], [3,8]]

这样matches[idx] 在df2 中有一个索引列表以与df1.loc[idx] 行合并,所以df1 中的第0 行和第1 行将与df2 中的第1,2,7,14 行合并,然后继续。

我将如何在这些列表中将df1 与df2 合并?就速度而言,试图通过 pandas 运行的逻辑是令人望而却步的,因此我必须从这些数据帧之间的匹配列表开始。

  • 试试pd.concat([df1, pd.Series(matches, name=\'match\')], axis=1).explode(\'match\').merge(df2, left_on=\'match\', right_index=True)。应该适用于数字索引。
  • 这就是解决方案,谢谢@MYousefi!

标签: python pandas dataframe


【解决方案1】:

根据@MYousefi,这是解决方案:

尝试

pd.concat([df1, pd.Series(matches, name='match')], axis=1).explode('match').merge(df2, left_on='match', right_index=True)

应该适用于数字索引。

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 2018-02-02
    • 2019-03-18
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2023-04-02
    • 2021-03-25
    相关资源
    最近更新 更多