代码之家  ›  专栏  ›  技术社区  ›  8-Bit Borges

Pandas-删除全为零的行,并使用已删除行的索引删除列

  •  1
  • 8-Bit Borges  · 技术社区  · 4 年前

    我的 df 是一个方形稀疏矩阵,形状如下: (3862, 3862)

          0   1    ... 3862
    0     0.0 0.0      0.0
    1     0.0 0.0      0.0
    ...
    3862  0.0 0.0  ... 0.0
    

    我需要去掉只有0.0的行,就像这样:

    df.loc[~(df==0.0).all(axis=1)]
    

    之后,我得到了形状为s的矩阵 (3819, 3862)


    但我需要保持矩阵的平方。

    那么,我如何跟踪已删除行的索引,以及从这些索引中删除列,以便最终得到形状呢 (3819,3819) ?

    3 回复  |  直到 4 年前
        1
  •  1
  •   BENY    4 年前

    你可以试试

    idx = df.index[(df==0.0).all(axis=1)]
    out = df.drop(idx,axis=1).drop(idx)
    
        2
  •  0
  •   piterbarg    4 年前

    使用转置运算符, .T :

    df = pd.DataFrame(columns = [0,1,2,3], data = [
            [0,0,0,0],
            [0,1,0,0],
            [0,0,0,1],
            [0,0,1,0],
            ])
    
    empty_rows = (df==0.0).all(axis=1)
    df.drop(df.index[empty_rows]).T.drop(df.index[empty_rows]).T
    
    

    输出(第0行和第0列都被删除

    
        1   2   3
    1   1   0   0
    2   0   0   1
    3   0   1   0
    

    或者 如果行和列索引值按顺序排列,则可以使用iloc:

    df.iloc[df.index[~empty_rows],df.index[~empty_rows]]
    

    这会产生相同的输出

        3
  •  0
  •   Davide Laghi    4 年前
    # Simple df example
    df = pd.DataFrame(
            [[0, 1, 2],
             [0, 0, 0],
             [3, 0, 0]])
    
    # Condition for rows to be kept
    condition = ~(df==0.0).all(axis=1)
    
    # Get the index of rows that satisfy condition
    idx2keep = df.loc[condition].index
    
    # Retain the columns and rows with good index
    df.loc[idx2keep, idx2keep]
    

    输出:

        0   2
    0   0   2
    2   3   0