ms25297
ms25297

Reputation: 51

How to convert a list of a list to be columns in a dataframe with an index?

So essentially I have a list of list for example:

a = [[1,2,3,4,5,6,7,8,9,10],
     [11,12,13,14,15,16,17,18,19,20]]

So each list has 10 numbers inside of it.I have an index list for example:

index = ['A','B','C','D','E','F','G','H','I','J']

I want to create a python dataframe to be structured as the following:

 A  1  11
 B  2  12
 C  3  13
 D  4  14 
 E  5  15
 F  6  16
 G  7  17 
 H  8  18
 I  9  19 
 J  10 20

Basically turning each list in a to be a column in the dataframe.

I tried the following:

df = pd.DataFrame(columns = a, index = index)

It ran but the lists didn't turn into the columns instead they were still the rows. Any easy way of doing this?

Upvotes: 0

Views: 589

Answers (2)

Animesh Mishra
Animesh Mishra

Reputation: 141

import pandas as pd
a = [[1,2,3,4,5,6,7,8,9,10],
     [11,12,13,14,15,16,17,18,19,20]]

index = ['A','B','C','D','E','F','G','H','I','J']

data = {f'col_{i}': column for i, column in enumerate(a)}

pd.DataFrame(data, index = index)

Convert the list of lists into a dictionary, with the column name being the key and the list to be used as a column the value. Pass that dictionary to the pd.DataFrame function to get the following output:

col_0   col_1
A   1   11
B   2   12
C   3   13
D   4   14
E   5   15
F   6   16
G   7   17
H   8   18
I   9   19
J   10  20

Upvotes: 0

Nicolas Gervais
Nicolas Gervais

Reputation: 36624

import pandas as pd
a = [[1,2,3,4,5,6,7,8,9,10],
     [11,12,13,14,15,16,17,18,19,20]]

index = ['A','B','C','D','E','F','G','H','I','J']

pd.DataFrame(a, columns=index).T

Upvotes: 1

Related Questions