Getting list of lists into pandas DataFrame
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 Question
00:42 Accepted answer (Score 329)
00:57 Answer 2 (Score 108)
01:27 Answer 3 (Score 8)
01:55 Answer 4 (Score 2)
02:11 Thank you
--
Full question
https://stackoverflow.com/questions/1911...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #datanitro
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 Question
00:42 Accepted answer (Score 329)
00:57 Answer 2 (Score 108)
01:27 Answer 3 (Score 8)
01:55 Answer 4 (Score 2)
02:11 Thank you
--
Full question
https://stackoverflow.com/questions/1911...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #datanitro
#avk47
ACCEPTED ANSWER
Score 342
Call the pd.DataFrame constructor directly:
df = pd.DataFrame(table, columns=headers)
df
Heading1 Heading2
0 1 2
1 3 4
ANSWER 2
Score 112
With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:
table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']
The output then is:
Heading1 Heading2
0 1 3
1 2 4
ANSWER 3
Score 10
Even without pop the list we can do with set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4
ANSWER 4
Score 4
From the table example, call DataFrame constructor as follow:
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
df = pd.DataFrame(table[1:], columns=table[0])