How to Convert a List to a DataFrame in Python


Often you may want to convert a list to a DataFrame in Python.

Fortunately this is easy to do using the function, which uses the following syntax:

pandas.DataFrame(data=None, index=None, columns=None, …)

where:

  • data: The data to convert into a DataFrame
  • index: Index to use for the resulting DataFrame
  • columns: Column labels to use for the resulting DataFrame

This tutorial provides several examples of how to use this function in practice.

Example 1: Convert One List to a DataFrame

The following code shows how to convert one list into a pandas DataFrame:

import pandas as pd

#create list that contains points scored by 10 basketball players
data = [4, 14, 17, 22, 26, 29, 33, 35, 35, 38]

#convert list to DataFrame
df = pd.DataFrame(data, columns=['points'])

#view resulting DataFrame
print(df)

       points
0       4
1      14
2      17
3      22
4      26
5      29
6      33
7      35

Example 2: Convert Several Lists to a DataFrame

The following code shows how to convert several lists into a pandas DataFrame:

import pandas as pd

#define lists
points = [4, 14, 17, 22, 26, 29, 33, 35, 35, 38]
rebounds = [1, 4, 4, 5, 8, 7, 5, 6, 9, 11]

#convert lists into a single list
data = []
data.append(points)
data.append(rebounds)

#view new list
data

[[4, 14, 17, 22, 26, 29, 33, 35, 35, 38], [1, 4, 4, 5, 8, 7, 5, 6, 9, 11]]

#convert list into DataFrame
df = pd.DataFrame(data).transpose()
df.columns=['points', 'rebounds']

#view resulting DataFrame
df

       points     rebounds
0       4         1
1      14         4
2      17         4
3      22         5
4      26         8
5      29         7
6      33         5
7      35         6
8      35         9
9      38         11

Example 3: Convert List of Lists to a DataFrame

The following code shows how to convert a list of lists into a pandas DataFrame:

import pandas as pd

#define list of lists
data = [[4, 1], [14, 4], [17, 4], [22, 5], [26, 8],
        [29, 7], [33, 5], [35, 6], [35, 9], [38,11]]

#convert list into DataFrame
df = pd.DataFrame(data, columns=['points', 'rebounds'])

#view resulting DataFrame
df

       points     rebounds
0       4         1
1      14         4
2      17         4
3      22         5
4      26         8
5      29         7
6      33         5
7      35         6
8      35         9
9      38         11

You can use the following code to quickly check how many rows and columns are in the resulting DataFrame:

#display number of rows and columns in DataFrame
df.shape

(10, 2)

And we can use the following code to retrieve the names of the columns in the resulting DataFrame:

#display column names of DataFrame
list(df)

['points', 'rebounds']

x