How to Create a DataFrame from Lists in Pandas

To create a DataFrame from list or nested lists in Pandas we can follow next steps:

Steps

  • Define the input data
    • flat list
    • nested list
    • dict of lists
  • Define the column names
  • Define the index - row names
  • Call the DataFrame constructor

Examples

In several examples we will cover the most popular cases of using lists to create DataFrames

Example 1 - Create Pandas DataFrame from List

Starting with a flat list which will be used for the values of the Future DataFrame. We are providing the index and the columns - which are optional. If the index and columns are not specified - then automatic ones will be used.

import pandas as pd
 
values = ['val_1', 'val_2', 'val_3']

df = pd.DataFrame(values, index = ['x', 'y', 'z'], columns = ['col_1'])

Output 1

col_1
x val_1
y val_2
z val_3

Example 2 - Create Pandas DataFrame from Nested Lists

The second example demonstrates creating a multi column DataFrame from nested lists. We can specify the column names as follows:

import pandas as pd

values = [['val_11', 'val_12'], ['val_21', 'val_22'], ['val_31', 'val_32']]
    
df = pd.DataFrame(values, columns = ['col_1', 'col_2'])

Output 2

col_1 col_2
0 val_11 val_12
1 val_21 val_22
2 val_31 val_32

Example 3 - Create Pandas DataFrame from dict of Lists

In this example we are creating multiple columns from several lists. Those lists are mapped with a dictionary to different columns.

If you want to learn more about creating DataFrames from dictionaries you can read this detailed article - How to Create DataFrame from Dictionary in Pandas?

import pandas as pd

col_1 = ["val_11", "val_21", "val_31"]
col_2 = ["val_21", "val_22", "val_32"]
 
data = {'col_1': col_1, 'col_2': col_2}
    
df = pd.DataFrame(data)

Output 3

col_1 col_2
0 val_11 val_21
1 val_21 val_22
2 val_31 val_32