Make a dataframe from list of variables which are lists

Question:

I have a list of variables in which each variable is a list. And I want to use that list to form a dataframe.

A=[1,2]
B=[4,3]
C=[A,B]

I want to create the dataframe using the list C that looks like this:

A B
1 4
2 3

I tried doing it like this

headers=['A','B']
df = pd.DataFrame(C, columns=headers)

But it doesn’t work. Any suggestions on how to achieve it?

Asked By: SHIVANSHU SAHOO

||

Answers:

You have a list of columns, but DataFrame expects a list of rows. You can transpose your list using zip

>>> A=[1,2]
>>> B=[4,3]
>>> C=[A,B]
>>> df = pd.DataFrame(zip(*C), columns=headers)
>>> df
   A  B
0  1  4
1  2  3

Or, zip A and B in the first place:

>>> C = zip(A, B)
>>> pd.DataFrame(C, columns=headers)
   A  B
0  1  4
1  2  3
Answered By: chepner
headers=['A','B']
df = pd.DataFrame(columns=headers)

for i in range(len(headers)):
    df[headers[i]] = pd.Series(C[i])
#output
   A  B
0  1  4
1  2  3
Answered By: Ignatius Reilly
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.