Pandas DataFrame from_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 from_records() classmethod converts a valid ndarray, tuple, or dictionary structure into a DataFrame format.

The syntax for this method is as follows:

classmethod DataFrame.from_records(data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None)
dataThis parameter is a valid ndarray, tuple, or dictionary structure.
indexA field of arrays for the index or a list containing a specific set.
excludeThe columns/fields to exclude from the conversion.
columnsThe column names to use in the conversion.
coerce_floatThis parameter tries to convert decimal values to floats.
nrowsIf an iterator, the number of rows to read in.

This example converts a list of tuples (an ndarray) containing four (4) fictitious Finxter users to a DataFrame.

data = np.array([(30022145, 'wildone92'), (30022192, 'AmyP'), 
                 (30022331, '1998_pete'), (30022345, 'RexTex')])
users_df = pd.DataFrame.from_records(data, columns=['ID', 'Username'])
  • Line [1] creates a list of tuples (ndarray) and saves it to the data variable.
  • Line [2] does the following:
    • creates a DataFrame from the data variable
    • sets the column names to clearly identify the data
  • Outputs the DataFrame to the terminal.



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.