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

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.

Syntax of Pandas DataFrame.to_numpy(): Method to convert dataframe to NumPu Array

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


Example: Convert pandas dataframe to NumPy arrayframe

Python NumPy Programs »

Comments and Discussions!

Copyright © 2023 All rights reserved.