【问题标题】:Check pandas df2.colA for occurrences of df1.id and write (df2.colB, df2.colC) into df1.colAB检查 pandas df2.colA 是否出现 df1.id 并将 (df2.colB, df2.colC) 写入 df1.colAB
【发布时间】:2021-11-04 10:22:33
【问题描述】:

我有两只熊猫df,它们的长度不同。 df1id 列中具有唯一 ID。这些 id 在df2.colA 中出现(多次)。我想将df2.colA 中所有出现的df1.id 的列表(以及df1.id == df2.colA 匹配索引处的另一列)添加到df1 的新列中。可以使用匹配的索引df2.colA,也可以使用所有匹配的其他行条目。

例子:

df1.id = [1, 2, 3, 4]

df2.colA = [3, 4, 4, 2, 1, 1] 

df2.colB = [5, 9, 6, 5, 8, 7]

这样我的操作会创建如下内容:

df1.colAB = [ [[1,8],[1,7]], [[2,5]], [[3,5]], [[4,9],[4,6]] ]

我尝试了很多映射方法、显式循环(超级慢)、检查isin 等。

【问题讨论】:

    标签: python pandas dataframe merge matching


    【解决方案1】:

    您可以使用 Pandas apply 遍历 df1 值的每一行,同时创建一个包含 df2.colA 中所有索引的列表。这可以通过在df2.colB 上使用Pandas indexloc 创建一个列表,其中包含df2.colA 中与df1.id 中的行匹配的所有索引。然后,在 apply 本身内使用 for 循环来创建匹配值列表。

    import pandas as pd
    # setup
    df1 = pd.DataFrame({'id':[1,2,3,4]})
    print(df1)
    
    df2 = pd.DataFrame({
            'colA' : [3, 4, 4, 2, 1, 1],
            'colB' : [5, 9, 6, 5, 8, 7]
    })
    print(df2)
    
    #code
    df1['colAB'] = df1['id'].apply(lambda row:
            [[row, idx] for idx in df2.loc[df2[df2.colA == row].index,'colB']])
    
    print(df1)
    

    df1的输出

       id             colAB
    0   1  [[1, 8], [1, 7]]
    1   2          [[2, 5]]
    2   3          [[3, 5]]
    3   4  [[4, 9], [4, 6]]
    

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多