Search code examples
pandasnumpydataframedrop

How to remove all rows and columns entirely with zeros in panda Dataframe


i want all rows and columns filled with zeros entirely need to be removed.

but it is returning only this.

      Box_deatils    1    5
0           1  0.0  0.0
1           2  1.0  0.0
2           3  1.0  0.0
3           4  0.0  0.0
4           5  0.0  0.0
5           6  0.0  1.0
  Box_deatils    1    5
0           1  0.0  0.0
1           2  1.0  0.0
2           3  1.0  0.0
3           4  0.0  0.0
4           5  0.0  0.0
5           6  0.0  1.0
 

row removal is not happening only column is happening

Please help to find whats wrong below.

Soln=[[0. 0. 0. 0. 0. 0.]
     [1. 0. 0. 0. 0. 0.]
     [1. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 1. 0.]]
    
    result=pd.DataFrame(Soln)

Final_result=result.loc[:,(result !=0).any(axis=0)]

print(Final_result)

Final_result=Final_result.loc[(Final_result !=0).any(axis=1)]

print(Final_result)

Solution

  • As I understand, row filled with zeros is actually a row where all "numeric-named" columns (in your case 1 and 5) have only zeros (the value in Box_deatils (or Box_details) column doesn't matter).

    To do it, you can run:

    df.drop(df.index[df.iloc[:, 1:].eq(0).all(axis=1)], inplace=True)
    

    and df now contains:

       Box_deatils    1    5
    1            2  1.0  0.0
    2            3  1.0  0.0
    5            6  0.0  1.0