How to create a Pandas DataFrame from List of Lists?
Create Pandas DataFrame from List of Lists
To create Pandas DataFrame from list of lists, you can pass this list of lists as data
argument to pandas.DataFrame().
Each inner list inside the outer list is transformed to a row in resulting DataFrame.
The syntax of DataFrame() class is
DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Examples
1. Create DataFrame from List of Lists
In this example, we will
- Import pandas package.
- Initialize a Python List of Lists.
- Create DataFrame by passing this list of lists object as
data
argument to pandas.DataFrame(). - pandas.DataFrame(list of lists) returns DataFrame.
Python Program
import pandas as pd
#list of lists
data = [['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3']]
df = pd.DataFrame(data)
print(df)
Output
0 1 2
0 a1 b1 c1
1 a2 b2 c2
2 a3 b3 c3
2. Create DataFrame from List of Lists, and with column names & index
In this example, we will
- Import pandas package.
- Initialize a Python List of Lists.
- Initialize a List for column name of DataFrame.
- Initialize a List for index of DataFrame.
- Create DataFrame by passing this list of lists object as
data
argument to pandas.DataFrame(). - pandas.DataFrame(list of lists) returns DataFrame.
Python Program
import pandas as pd
#list of lists
data = [['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3']]
columns = ['aN', 'bN', 'cN']
index = [1, 2, 3]
df = pd.DataFrame(data, index, columns)
print(df)
Output
aN bN cN
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
3. Create DataFrame from List of Lists with different list lengths
If the inner lists have different lengths, the lists with lesser values will be transformed to rows with appended values of None
to match the length of longest row in the DataFrame.
In this example, we will
- Import pandas package.
- Initialize a Python List of Lists such that inner lists are of different lengths.
- Create DataFrame by passing this list of lists object for
data
parameter to pandas.DataFrame() constructor. - pandas.DataFrame(list of lists) returns DataFrame.
Python Program
import pandas as pd
#list of lists
data = [['a1', 'b1', 'c1', 'd1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3']]
df = pd.DataFrame(data)
print(df)
Output
0 1 2 3
0 a1 b1 c1 d1
1 a2 b2 c2 None
2 a3 b3 c3 None
Summary
In this Pandas Tutorial, we learned how to create a Pandas DataFrame from Python List of Lists, with the help of well detailed examples.