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
Advertisement
Answer
Remember that df.explode
does not do its work in place. It RETURNS a new dataframe with the changes:
JavaScript
x
15
15
1
import pandas as pd
2
3
data = [
4
[ 0, [1,2,3], [4,5,6], 7 ],
5
[ 0, [1,2,3], [4,5,6], 7 ],
6
[ 0, [1,2,3], [4,5,6], 7 ],
7
[ 0, [1,2,3], [4,5,6], 7 ],
8
[ 0, [1,2,3], [4,5,6], 7 ]
9
]
10
11
df = pd.DataFrame( data, columns=['one', 'two','three','four'] )
12
print(df)
13
df2 = df.explode('two')
14
print(df2)
15
Output:
JavaScript
1
23
23
1
one two three four
2
0 0 [1, 2, 3] [4, 5, 6] 7
3
1 0 [1, 2, 3] [4, 5, 6] 7
4
2 0 [1, 2, 3] [4, 5, 6] 7
5
3 0 [1, 2, 3] [4, 5, 6] 7
6
4 0 [1, 2, 3] [4, 5, 6] 7
7
one two three four
8
0 0 1 [4, 5, 6] 7
9
0 0 2 [4, 5, 6] 7
10
0 0 3 [4, 5, 6] 7
11
1 0 1 [4, 5, 6] 7
12
1 0 2 [4, 5, 6] 7
13
1 0 3 [4, 5, 6] 7
14
2 0 1 [4, 5, 6] 7
15
2 0 2 [4, 5, 6] 7
16
2 0 3 [4, 5, 6] 7
17
3 0 1 [4, 5, 6] 7
18
3 0 2 [4, 5, 6] 7
19
3 0 3 [4, 5, 6] 7
20
4 0 1 [4, 5, 6] 7
21
4 0 2 [4, 5, 6] 7
22
4 0 3 [4, 5, 6] 7
23