15.1 C
London
Friday, July 5, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Convert a List to a DataFrame Row in Python

How to Convert a List to a DataFrame Row in Python

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories