Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove zero from each column and rearranging it with python pandas/numpy

I am a total novice in python and currently I am stumbled with a simple but tricky situation. Is it possible to remove all these zeroes and rearrange the column from this :

A B C D E F
10 10 5 0 0 0
0 0 0 13 3 4
0 13 41 55 0 0
0 0 31 30 21 0
11 19 20 0 0 0 

To be something like this:

A B C 
10 10 5
13 3 4
13 41 55
31 30 21
11 19 20
like image 766
ShortHair Avatar asked Mar 02 '23 03:03

ShortHair


1 Answers

Assuming all rows have the same amount of zeros:

a = df.to_numpy()
a = a[a!=0].reshape(-1,3)

pd.DataFrame(a, columns=df.columns[:a.shape[1]])

    A   B   C
0  10  10   5
1  13   3   4
2  13  41  55
3  31  30  21
4  11  19  20
like image 154
yatu Avatar answered Apr 10 '23 09:04

yatu