Python Convert a list into a dataframe

I have a list that consists of lists. Looks something like this:

[[1,2,3,4,5],['john','leo','steve','ben','sally'],['22','55','66','11','33'],['blue','green','red','yellow','pink']]

I want to convert this into a dataframe that looks like this:

      1     2     3      4     5
0  john   leo steve    ben sally
1    22    55    66     11    33
2  blue green   red yellow  pink

Any suggestions?

I tried to play around with the reshape function, but I can't get it to work.

I also tried looking at ValueError: Shape of passed values is (1, 6), indices imply (6, 6) but that didn't help either.

Upvotes: 2

Views: 82

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150725

How about:

pd.DataFrame(data[1:], columns=data[0])

Output:

      1      2      3       4      5
0  john    leo  steve     ben  sally
1    22     55     66      11     33
2  blue  green    red  yellow   pink

Upvotes: 2

Dani Mesejo
Dani Mesejo

Reputation: 61900

You could do:

import pandas as pd


columns, *data = [[1,2,3,4,5],['john','leo','steve','ben','sally'],['22','55','66','11','33'],
                  ['blue','green','red','yellow','pink']]
df = pd.DataFrame(data=data, columns=columns)
print(df)

Output

      1      2      3       4      5
0  john    leo  steve     ben  sally
1    22     55     66      11     33
2  blue  green    red  yellow   pink

Upvotes: 2

Related Questions