How to Convert a List to a DataFrame Row in Python


You can use the following syntax to convert a list into a DataFrame row in Python:

#define list
x = [4, 5, 8, 'A' 'B']

#convert list to DataFrame
df = pd.DataFrame(x).T

And you can use the following syntax to convert a list of lists into several rows of a DataFrame:

#define list of lists
big_list = [[4, 5, 6, 'B'],
            [4, 2, 1, 'A'],
            [12, 4, 8, 'C']]

#convert list of lists into DataFrame
df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4'], data=big_list)

The following examples show how to use each of these functions in practice.

Example 1: Convert a List into a DataFrame Row

The following code shows how to convert a single list into a DataFrame with one row in Python:

import pandas as pd

#define list
x = [4, 5, 8, 'Mavericks']

#convert list to DataFrame
df = pd.DataFrame(x).T

#specify column names of DataFrame
df.columns = ['Points', 'Assists', 'Rebounds', 'Team']

#display DataFrame
print(df)

  Points Assists Rebounds       Team
0      4       5        8  Mavericks

Example 2: Convert a List of Lists into Several DataFrame Rows

The following code shows how to convert a list of lists into a DataFrame with several rows in Python:

import pandas as pd

#define list of lists
big_list = [[6, 7, 12, 'Mavericks'],
            [4, 2, 1, 'Lakers'],
            [12, 4, 8, 'Spurs']]

#convert list of lists into DataFrame
df = pd.DataFrame(columns=['Points', 'Assists', 'Rebounds', 'Team'], data=big_list)

#display DataFrame
print(df)

        Points	Assists	Rebounds  Team
0	6	7	12	  Mavericks
1	4	2	1	  Lakers
2	12	4	8	  Spurs

We can verify the number of rows and columns of the resulting DataFrame by using the .shape() function:

print(df.shape)

(3, 4)

This tells us that the resulting DataFrame has 3 rows and 4 columns.

Additional Resources

How to Convert a DataFrame to a List in Pandas
How to Convert a Dictionary to a DataFrame in Pandas
How to Create a Pandas DataFrame from a NumPy Array

Leave a Reply

Your email address will not be published.