carl_pch carl_pch - 1 month ago 8
Python Question

Converting python lists to pd.DataFrame

If I have 3 python lists items:

list1 = [1,2,3]
list2 = ['a','b','c']
list3 = ['I',"II","III"]


And my goal is to build a pd.DataFrame using list1 as index and the rest as columns:

list2 list3
1 "a" "I"
2 "b" "II"
3 "c" "III"


What would be the most efficient way to do it? Most of the similar questions I found here are joining list of lists or dictionary, but my data only has a simple structure and a natural order, so it should be simpler?

I have checked both
pd.Series
and
pd.DataFrame
documentation, but examples are also mostly about joining
Series
or
DataFrame
together.

Answer

Use the DataFrame constructor:

In [1]: import pandas as pd, numpy as np

In [2]: list1 = [1,2,3]

In [3]: list2 = ['a','b','c']

In [4]: list3 = ['I',"II","III"]

In [5]: pd.DataFrame({'list2':list2,'list3':list3}, index=list1)
Out[5]: 
  list2 list3
1     a     I
2     b    II
3     c   III

In [6]: 
Comments