首页 文章

删除所有列中具有相同值的行

提问于
浏览
1

我有一个pandas数据框,我试图根据具有完全相同值的所有列删除行 . 这是一个帮助理解这个想法的例子 .

输入:

index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 1     2  2  2  2  2  2
 2     5  5  5  5  5  5 
 3     7  7  6  7  7  7

输出:

index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 3     7  7  6  7  7  7

这里可以有很多列 .

3 回答

  • 4

    使用数字DataFrames执行此操作的有效方法是使用标准偏差(仅当所有值都相同时才为0):

    df[df.std(axis=1) > 0]
    Out: 
       A  B  C  D  E  F
    0  1  2  3  1  3  4
    3  7  7  6  7  7  7
    

    40k行的计时:

    %timeit df[df.std(axis=1) > 0]
    1000 loops, best of 3: 1.69 ms per loop
    
    %timeit df[df.nunique(1)>1]
    1 loop, best of 3: 2.62 s per loop
    
  • 2

    另一种有效的方式(并不像@ ayhan的解决方案那么快)方式:

    In [17]: df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
    Out[17]:
           A  B  C  D  E  F
    index
    0      1  2  3  1  3  4
    3      7  7  6  7  7  7
    

    时间为40.000行DF:

    In [19]: df.shape
    Out[19]: (40000, 6)
    
    In [20]: %timeit df[df.std(axis=1) > 0]
    5.62 ms ± 162 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
    In [21]: %timeit df[df.nunique(1)>1]
    9.87 s ± 104 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    In [23]: %timeit df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
    13 ms ± 86.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
  • 2

    使用 nunique

    df=df[df.nunique(1)>1]
    df
    Out[286]: 
           A  B  C  D  E  F
    index                  
    0      1  2  3  1  3  4
    3      7  7  6  7  7  7
    

相关问题