Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas explode column only non zero values

Tags:

python

pandas

How to filter tolist or values below to get only non-zeros

import pandas as pd
df = pd.DataFrame({'A':[0,2,3],'B':[2,0,4], 'C': [3,4,0]})
df['D']=df[['A','B','C']].values.tolist()
df.explode('D')

Data

    A   B   C
0   0   2   3
1   2   0   4
2   3   4   0

On Explode on Column D rows now becomes 9. But i want 4 rows in the output

Expected result

    A   B   C   D
0   0   2   3   2
0   0   2   3   3
1   2   0   4   2
1   2   0   4   4 
2   3   4   0   3
2   3   4   0   4

I got list(filter(None, [1,0,2,3,0])) to return only non-zeros. But not sure how to apply it in the above code

like image 972
sjd Avatar asked Jan 23 '26 05:01

sjd


2 Answers

index.repeat

m = df.ne(0)
df.loc[df.index.repeat(m.sum(1))].assign(D=df.values[m])

   A  B  C  D
0  0  2  3  2
0  0  2  3  3
1  2  0  4  2
1  2  0  4  4
2  3  4  0  3
2  3  4  0  4
like image 92
Shubham Sharma Avatar answered Jan 25 '26 17:01

Shubham Sharma


Simpliest is query:

df['D']=df[['A','B','C']].values.tolist()
df.explode('D').query('D != 0')

Output:

   A  B  C  D
0  0  2  3  2
0  0  2  3  3
1  2  0  4  2
1  2  0  4  4
2  3  4  0  3
2  3  4  0  4
like image 21
Quang Hoang Avatar answered Jan 25 '26 19:01

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!