Hemantchandru naik
Hemantchandru naik

Reputation: 101

Ungroup pandas dataframe column values separated by comma

Hello I Have pandas dataframe which is grouped wanted to ungroup the dataframe the column values are separated comma the dataframe which is looking as below

 col1             col2   name  exams 

0,0,0                0,0,0,   A1   exm1,exm2, exm3
0,1,0,20           0,0,2,20   A2   exm1,exm2, exm4, exm5
0,0,0,30           0,0,20,20  A3   exm1,exm2, exm3, exm5

output how I wanted

   col1   col2  name exam
    0       0    A1   exm1
    0       0    A1   exm2
    0       0    A1   exm3
    0       0    A2   exm1
    1       0    A2   exm2
    0       2    A2   exm4
    20      20   A2   exm5
     ..............
    30      20   A3   exm5

I am tried with Split (explode) pandas dataframe string entry to separate rows but not able get proper approach any one please give me suggestion how can I get my output

Upvotes: 0

Views: 292

Answers (1)

BENY
BENY

Reputation: 323316

Try with explode, notice , explode is the new function after pandas 0.25.0

df[['col1','col2','exams']]=df[['col1','col2','exams']].apply(lambda x : x.str.split(','))
df = df.join(pd.concat([df.pop(x).explode() for x in ['col1','col2','exams']],axis=1))
Out[62]: 
  name col1 col2 exams
0   A1    0    0  exm1
0   A1    0    0  exm2
0   A1    0    0  exm3
1   A2    0    0  exm1
1   A2    1    0  exm2
1   A2    0    2  exm4
1   A2   20   20  exm5
2   A3    0    0  exm1
2   A3    0    0  exm2
2   A3    0   20  exm3
2   A3   30   20  exm5

Upvotes: 2

Related Questions