emax
emax

Reputation: 7245

Python: how to pivot a dataframe that contains lists?

I have a pandas dataframe that looks like the following

df
     A        B
0   'X1'    [3,2,1,5]
1   'X2'    [0,-2,1,2]
2   'X3'    [5,1,1,-6]

I would like to get a dataframe like the following one:

df
    X1    X2    X3
0   3     0     5
1   2    -2     1
2   1     1     1
3   5     2     6

Upvotes: 0

Views: 28

Answers (1)

jezrael
jezrael

Reputation: 863166

Convert column from B to DataFrame with index by A column and then transpose by DataFrame.T:

df = pd.DataFrame(df.B.tolist(), index=df.A.tolist()).T
print (df)
   'X1'  'X2'  'X3'
0     3     0     5
1     2    -2     1
2     1     1     1
3     5     2    -6

df = pd.DataFrame(df.B.tolist(), index=df.A.str.strip("'").tolist()).T
print (df)
   X1  X2  X3
0   3   0   5
1   2  -2   1
2   1   1   1
3   5   2  -6

Upvotes: 5

Related Questions