Convert Pandas DataFrame to NumPy Array

The NumPy array is the homogeneous multidimensional array , along with a large collection of high-level mathematical functions to operate on these arrays.

Convert pandas dataframe to NumPy array

  1. Usng to_numpy()
df.to_numpy()
  1. Using to_records()
df.to_records()
  1. Using asarray()
np.asarray(df)

Lets craete a DataFrame..

import pandas as pd import numpy as np df = pd.DataFrame() df['TotalMarks'] = [82, 38, 63,22,55,40] df

Dataframe to numpy
TotalMarks 0 82 1 38 2 63 3 22 4 55 5 40

Convert pandas dataframe to NumPy array usng to_numpy()

df.to_numpy()
array([[82], [38], [63], [22], [55], [40]], dtype=int64)
Checking Type
type(df.to_numpy())
numpy.ndarray

NumPy array dtype

In the above output you can see the dtype=int64 . You can also provide dtype=int64 as parameters.
df.to_numpy(dtype ='float32')
array([[82.], [38.], [63.], [22.], [55.], [40.]], dtype=float32)

Convert pandas dataframe to NumPy array usng to_records()

df.to_records()
rec.array([(0, 82), (1, 38), (2, 63), (3, 22), (4, 55), (5, 40)], dtype=[('index', '<i8'), ('TotalMarks', '<i8')])
Checking Type
type(df.to_records())
numpy.recarray
Note that this is a recarray rather than an numpy.ndarray. You could move the result in to regular numpy array by calling its constructor as np.array(df.to_records()) .
np.array(df.to_records())
array([(0, 82), (1, 38), (2, 63), (3, 22), (4, 55), (5, 40)], dtype=(numpy.record, [('index', '<i8'), ('TotalMarks', '<i8')]))
Checking Type
type(np.array(df.to_records()))
numpy.ndarray

Convert pandas dataframe to NumPy array usng asarray()

np.asarray(df)

numpy asarray
array([[82], [38], [63], [22], [55], [40]], dtype=int64)
Checking Type
type(np.asarray(df))
numpy.ndarray

df.values and df.as_matrix()

You can use df.values and df.as_matrix() to convert dataframe to NumPy array. But these two methods are depreciated. If you visit the v0.24 docs for .values, you will see a big red warning that says:
Warning: We recommend using DataFrame.to_numpy() instead.