Skip to content
Advertisement

pandas explode column only non zero values

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement