Table of Contents
Converting a list to a DataFrame row in Python is a useful process for organizing and manipulating data. This can be achieved by using the pandas library, which provides a function called “DataFrame” that allows users to convert a list into a row within a DataFrame. By specifying the list as the input and providing appropriate column labels, the function will create a new row in the DataFrame with the list values. This allows for easy integration of lists into larger datasets and simplifies the process of organizing data in a tabular format.
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.