Pandas DataFrame - Convert row to list


Pandas DataFrame - Convert row to list

In Pandas, to convert a row in a DataFrame to a list, you can use tolist() method.

Each row of a DataFrame can be accessed as a Series object, and Series objects have a method tolist() that returns the list representation of the Series object.

The syntax to use tolist() method to convert a DataFrame row to a list is

row.tolist()

In this tutorial, we will go through some examples, with step by step explanation of how to convert a given row in DataFrame to a list.

Example

1. Convert row in DataFrame to list

In this example, we are given a DataFrame in df_input. We have to convert the second row in this DataFrame to a list object.

Steps

  1. Given a DataFrame in df_input with three columns 'A', 'B', and 'C', and five rows.
df_input = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [10, 20, 30, 40, 50]})
  1. Select the second row, and store it in a variable.
second_row = df_input.iloc[1]
  1. Call tolist() method on second_row, and store the returned value.
second_row_list = second_row.tolist()
  1. You may print the list to output using print() function.
print(second_row_list)

Program

The complete program to convert a row in a given DataFrame to a list.

Python Program

import pandas as pd

# Take a DataFrame
df_input = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [10, 20, 30, 40, 50]})

# Select row
second_row = df_input.iloc[1]

# Convert row to list
second_row_list = second_row.tolist()

# Print the list
print(second_row_list)

Output

[4, 3, 20]

Summary

In this Pandas Tutorial, we learned how to convert a given row in a DataFrame to a list using tolist() method, with examples.