Open In App

Create a list from rows in Pandas dataframe

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python list is easy to work with and also list has a lot of in-built functions to do a whole lot of operations on lists. Pandas dataframe’s columns consist of series but unlike the columns, Pandas dataframe rows are not having any similar association. In this post, we are going to discuss several ways in which we can extract the whole row of the dataframe at a time.

Solution #1:

In order to iterate over the rows of the Pandas dataframe we can use

DataFrame.iterrows()

function and then we can append the data of each row to the end of the list.

Python
# importing pandas as pd
import pandas as pd

# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
                   'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                   'Cost':[10000, 5000, 15000, 2000]})

# Print the dataframe
print(df)


Output :

Now we will use the

DataFrame.iterrows()

function to iterate over each of the row of the given Dataframe and construct a list out of the data of each row.

Python
# Create an empty list
Row_list =[]

# Iterate over each row
for index, rows in df.iterrows():
    # Create list for the current row
    my_list =[rows.Date, rows.Event, rows.Cost]
    
    # append the list to the final list
    Row_list.append(my_list)

# Print the list
print(Row_list)

Output :

As we can see in the output, we have successfully extracted each row of the given dataframe into a list. Just like any other Python’s list we can perform any list operation on the extracted list.

Python
# Find the length of the newly 
# created list
print(len(Row_list))

# Print the first 3 elements
print(Row_list[:3])

Output :

Solution #2:

In order to iterate over the rows of the Pandas dataframe we can use

DataFrame.itertuples()

function and then we can append the data of each row to the end of the list.

Python
# importing pandas as pd
import pandas as pd

# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
                   'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                   'Cost':[10000, 5000, 15000, 2000]})

# Print the dataframe
print(df)


Output :

Now we will use the

DataFrame.itertuples()

function to iterate over each of the row of the given Dataframe and construct a list out of the data of each row.

Python
# Create an empty list
Row_list =[]

# Iterate over each row
for rows in df.itertuples():
    # Create list for the current row
    my_list =[rows.Date, rows.Event, rows.Cost]
    
    # append the list to the final list
    Row_list.append(my_list)

# Print the list
print(Row_list)

Output :

As we can see in the output, we have successfully extracted each row of the given dataframe into a list. Just like any other Python’s list we can perform any list operation on the extracted list.

Python
# Find the length of the newly 
# created list
print(len(Row_list))

# Print the first 3 elements
print(Row_list[:3])

Output :

Create a list from rows in Pandas dataframe – FAQs

How to Create a List from a DataFrame Row

To create a list from a row in a DataFrame, you can use the .iloc method to access the row and then convert it to a list using .tolist():

import pandas as pd

# Example DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
})

# Select the first row and convert to a list
row_list = df.iloc[0].tolist()
print(row_list) # Output: [1, 4, 7]

How to Create a DataFrame from a List of Rows in Pandas

If you have a list where each element (which is itself a list) represents a row, you can easily convert this into a DataFrame by passing the list to the DataFrame constructor and specifying column names:

# List of lists where each inner list is a row
data = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

# Create DataFrame
df_new = pd.DataFrame(data, columns=['A', 'B', 'C'])
print(df_new)

How to Make a List in a Pandas DataFrame

To insert or store lists within a DataFrame, you can directly assign lists to a new column or modify an existing column:

# Adding a new column where each entry is a list
df['D'] = [[10, 11], [12, 13], [14, 15]]
print(df)

How to Append Pandas Rows to List

If you want to append multiple rows from a DataFrame to a list, where each row is converted into a list:

# Create an empty list
all_rows = []

# Append each row as a list to 'all_rows'
for index, row in df.iterrows():
all_rows.append(row.tolist())

print(all_rows)

How to Combine Multiple Rows into One List in Pandas

To combine multiple rows into a single list, where all cell values across the rows are gathered into one flat list, you can use list comprehension combined with a flattening operation:

# Combine all DataFrame rows into a single list
combined_list = [item for sublist in df.values.tolist() for item in sublist]
print(combined_list)


Next Article

Similar Reads

three90RightbarBannerImg