4

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
soMarios
  • 24,472
  • 8
  • 28
  • 43
ShortHair
  • 109
  • 3

3 Answers3

5

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
yatu
  • 80,714
  • 11
  • 64
  • 111
1

we can use stack and cumcount to re-create your columns.

first lets use mask to turn any 0 into NaN values. which are dropped by default in the stack

from string import ascii_uppercase #for your columns.

letters = dict(enumerate(list(ascii_uppercase)))
s  = df.mask(df.eq(0)).stack().reset_index(1,drop=True).to_frame()

df1 = (
    s.set_index(s.groupby(level=0).cumcount().map(letters), append=True)
    .unstack(1)
    .droplevel(0, 1)
)

print(df1)

   A   B   C
0  10  10   5
1  13   3   4
2  13  41  55
3  31  30  21
4  11  19  20
Umar.H
  • 20,495
  • 6
  • 30
  • 59
1

You could use apply numpy's trim_zeros along the columns :

Note that the assumption here is that your zeros are the head or tail of each row

cleaned = np.apply_along_axis(np.trim_zeros, 1, df.to_numpy())
pd.DataFrame(cleaned, columns=df.columns[: cleaned.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
sammywemmy
  • 22,944
  • 4
  • 14
  • 28