Pandas DataFrame – Convert row to dictionary

Pandas DataFrame – Convert row to dictionary

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

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

The syntax to use to_dict() method to convert a DataFrame row to a dictionary is

row.to_dict()

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 dictionary.

Examples

1. Convert row in given DataFrame to dictionary

In this example, we are given a DataFrame in df_input. We have to convert the second row in this DataFrame to a dictionary 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 to_dict() method on second_row, and store the returned value.
second_row_dict = second_row.to_dict()
  1. You may print the resulting dictionary to output using print() function.
print(second_row_dict)

Program

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

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 dictionary
second_row_dict = second_row.to_dict()

# Print the dictionary
print(second_row_dict)
Run Code Copy

Output

{'A': 4, 'B': 3, 'C': 20}

The column labels of DataFrame have become the keys in dictionary, and the row values for each column of the DataFrame have become the values in dictionary.

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍