简体   繁体   中英

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?

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM