Pandas DataFrame to_records() Method

Rate this post


Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.

Feel free to view the PyCharm installation guide for the required libraries.

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np


The to_records() method converts a valid DataFrame structure to a NumPy record array. The index is included as the first field if requested.

The syntax for this method is as follows:

DataFrame.to_records(index=True, column_dtypes=None, index_dtypes=None)
indexThis parameter, if True, includes the index in the record array.
This value saves to the index field or index label.
column_dtypesThe data type to store the columns. If a dictionary, each column maps accordingly.
index_dtypesThe data type to store index levels. If a dictionary, each index level and indices map accordingly.

This example reads in the file’s first (5) rows / three (3) columns to a DataFrame. This DataFrame then converts to records.

Click here to save this CSV file and move it to the current working directory.

df = pd.read_csv('finxters.csv', usecols=['FID', 'First_Name', 'Last_Name']).head()
result = df.to_records()
  • Line [1] reads in the first five (5) rows (head) and three (3) columns (usecols) of the finxters.csv file. The output saves to a DataFrame (df).
  • Line [2] outputs the DataFrame to the terminal.
  • Line [3] converts the DataFrame (df) to records. The output saves to result.
  • Line [4] outputs the result to the terminal.

Output – df

Output – result

[(0, 30022145, 'Steve', 'Hamilton') (1, 30022192, 'Amy', 'Pullister')
(2, 30022331, 'Peter', 'Dunn') (3, 30022345, 'Marcus', 'Williams')
(4, 30022359, 'Alice', 'Miiller')]

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.