Skip to content
Advertisement

df.explode() function not working in python

I am facing a weird issue, I have a column name ‘window’ in a data frame and it has a list of values i.e., [3,9,45,78]. I am trying to explode this column using df.explode(‘window’) but this is doing no job. datatype of ‘window’ column is object. I have checked my pandas version it is – 1.3.4

dataframe example

Advertisement

Answer

Remember that df.explode does not do its work in place. It RETURNS a new dataframe with the changes:

import pandas as pd

data = [
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ]
]

df = pd.DataFrame( data, columns=['one', 'two','three','four'] )
print(df)
df2 = df.explode('two')
print(df2)

Output:

   one        two      three  four
0    0  [1, 2, 3]  [4, 5, 6]     7
1    0  [1, 2, 3]  [4, 5, 6]     7
2    0  [1, 2, 3]  [4, 5, 6]     7
3    0  [1, 2, 3]  [4, 5, 6]     7
4    0  [1, 2, 3]  [4, 5, 6]     7
   one two      three  four
0    0   1  [4, 5, 6]     7
0    0   2  [4, 5, 6]     7
0    0   3  [4, 5, 6]     7
1    0   1  [4, 5, 6]     7
1    0   2  [4, 5, 6]     7
1    0   3  [4, 5, 6]     7
2    0   1  [4, 5, 6]     7
2    0   2  [4, 5, 6]     7
2    0   3  [4, 5, 6]     7
3    0   1  [4, 5, 6]     7
3    0   2  [4, 5, 6]     7
3    0   3  [4, 5, 6]     7
4    0   1  [4, 5, 6]     7
4    0   2  [4, 5, 6]     7
4    0   3  [4, 5, 6]     7
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement