【问题标题】:Comparing two dataframe and output the index of the duplicated row once比较两个数据帧并输出一次重复行的索引
【发布时间】:2019-10-03 14:48:59
【问题描述】:

我需要帮助来比较两个数据框。例如:

第一个数据帧是

df_1 = 
    0   1   2   3   4   5
0   1   1   1   1   1   1
1   2   2   2   2   2   2
2   3   3   3   3   3   3
3   4   4   4   4   4   4
4   2   2   2   2   2   2
5   5   5   5   5   5   5
6   1   1   1   1   1   1
7   6   6   6   6   6   6

第二个数据框是

df_2 = 
    0   1   2   3   4   5
0   1   1   1   1   1   1
1   2   2   2   2   2   2
2   3   3   3   3   3   3
3   4   4   4   4   4   4
4   5   5   5   5   5   5
5   6   6   6   6   6   6

我想知道是否有一种方法(不使用 for 循环)来查找具有相同 df_2 行值的 df_1 行的索引。在上面的示例中,我的预期输出如下

index = 
0
1
2
3
5
7

上面“index”变量的列大小应该与df_2的列大小相同。

如果 df_2 的同一行在 df_1 中重复多次,我只需要第一次出现的索引,这就是为什么我不需要索引 4 和 6。

请帮忙。非常感谢!

汤米

【问题讨论】:

    标签: pandas dataframe indexing find


    【解决方案1】:
    检查解决方案
    df1=pd.DataFrame({'0':[1,2,3,4,2,5,1,6],
                     '1':[1,2,3,4,2,5,1,6],
                    '2':[1,2,3,4,2,5,1,6],
                     '3':[1,2,3,4,2,5,1,6],
                     '4':[1,2,3,4,2,5,1,6],
                    '5':[1,2,3,4,2,5,1,6]})
    
    df1=pd.DataFrame({'0':[1,2,3,4,5,6],
                     '1':[1,2,3,4,5,66],
                    '2':[1,2,3,4,5,6],
                     '3':[1,2,3,4,5,66],
                     '4':[1,2,3,4,5,6],
                    '5':[1,2,3,4,5,6]})
    df1[df1.isin(df2)].index.values.tolist()
    
    ### Output
    [0, 1, 2, 3, 4, 5, 6, 7]
    

    【讨论】:

      【解决方案2】:

      使用DataFrame.mergeDataFrame.drop_duplicatesDataFrame.reset_index 将索引转换为列以避免丢失索引值,最后选择名为index 的列:

      s = df_2.merge(df_1.drop_duplicates().reset_index())['index']
      print (s)
      0    0
      1    1
      2    2
      3    3
      4    5
      5    7
      Name: index, dtype: int64
      

      详情

      print (df_2.merge(df_1.drop_duplicates().reset_index()))
         0  1  2  3  4  5  index
      0  1  1  1  1  1  1      0
      1  2  2  2  2  2  2      1
      2  3  3  3  3  3  3      2
      3  4  4  4  4  4  4      3
      4  5  5  5  5  5  5      5
      5  6  6  6  6  6  6      7
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 2020-07-31
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 2019-07-21
        • 1970-01-01
        相关资源
        最近更新 更多