Convert pandas dataframe to NumPy array

Convert dataframe to NumPy array: In this tutorial, we will learn about the easiest way to convert pandas dataframe to NumPy array with the help of examples. By Pranit Sharma Last updated : May 23, 2023

Problem statement

Given a Pandas DataFrame, we have to convert it into a NumPy array.

Converting pandas dataframe to NumPy array

To convert Pandas dataframe to a NumPy array, use DataFrame.to_numpy() method, the method is called with this dataframe, accepts the optional parameters such as dtype, copy, na_value. It returns an array of numpy.ndarray type.


DataFrame.to_numpy(dtype=None, copy=False, na_value=_NoDefault.no_default)

These parameters are optional. Where dtype is the data type that we are passing, copy ensures that the returned value is not a view on another array, and na_value uses for the missing value.

Let us understand with the help of an example,

Python program to convert pandas dataframe to NumPy array

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating dataframe
df = pd.DataFrame(data=np.random.randint(0,50,(2,5)),columns=list('12345'))

# Display original DataFrame
print("Original DataFrame 1:\n",df,"\n")

# Converting df to numpy array
res = df.to_numpy()

# Display Result


The output of the above program is:

Example: Convert pandas dataframe to NumPy arrayframe

Python NumPy Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.