代码之家  ›  专栏  ›  技术社区  ›  azal

根据另一个数据帧中的条件删除数据帧中的行

  •  0
  • azal  · 技术社区  · 6 年前

    我熟悉如何根据以下条件删除数据帧中的行:

    df1 = df1.drop(df1[<some boolean condition>].index)
    

    让df1和df2大小相等。问题是删除DF2中满足上述DF1条件的相同索引行。我在寻找一个优雅的解决方案,而不是保留索引,然后针对df2再次对它们进行迭代。

    例子:

             df1                
        index  value
        1        4
        2        5
        3        6
        4        3
        1        1
        2        5
        1        3
        2        3
        3        2
        4        2
        5        1
        6        7
        7        12
    
          df2   
     index  value
        1        4
        2        5
        3        7
        4        3
        1        1
        2        109
        1        44
        2        3
        3        2
        4        2
        5        1
        6        7
        7        12
    

    索引不是连续的,因此简单的df.drop无法工作。它基于以前创建的组。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Edeki Okoh    6 年前

    首先,应该在数据帧中修复索引。除非索引是连续的,否则您要执行的操作将不起作用,因为您将通过按索引删除来删除多行。你应该尽量避免 many to many relationships in data analytics - they simply cause more problems then they solve )

    尝试如下操作:

    df1.reset_index()
    df2.reset_index()
    for indexes, row in df1.iterrows():
        if df1.columnname = 2: #imaginary value, place Boolean condition here
           df1.drop(df1.index[[indexes]])
           df2.drop(df2.index[[indexes]])