Pandas Dataframe.to_numpy() – Convert dataframe to Numpy array

Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of Dataframe.to_numpy() method.

Syntax: Dataframe.to_numpy(dtype = None, copy = False)

Parameters:
dtype: Data type which we are passing like str.
copy: [bool, default False] Ensures that the returned value is a not a view on another array.

Returns:
numpy.ndarray

To get the link to csv file, click on nba.csv



Example 1: Changing the DataFrame into numpy array by using a method DataFrame.to_numpy(). Always remember that when dealing with lot of data you should clean the data first to get the high accuracy. Although in this code we use the first five values of Weight column by using .head() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas
import pandas as pd 
   
# reading the csv  
data = pd.read_csv("nba.csv"
      
data.dropna(inplace = True)
   
# creating DataFrame form weight column
gfg = pd.DataFrame(data['Weight'].head())
   
# using to_numpy() function
print(gfg.to_numpy())

chevron_right


Output:

[[180.]
 [235.]
 [185.]
 [235.]
 [238.]]

Example 2: In this code we are just giving the parameters in the same code. So we provide the dtype here.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas
import pandas as pd 
   
# read csv file  
data = pd.read_csv("nba.csv"
      
data.dropna(inplace = True)
   
# creating DataFrame form weight column
gfg = pd.DataFrame(data['Weight'].head())
   
# providing dtype
print(gfg.to_numpy(dtype ='float32'))

chevron_right


Output:

[[180.]
 [235.]
 [185.]
 [235.]
 [238.]]

Example 3: Validating the type of the array after conversion.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas 
import pandas as pd 
   
# reading csv  
data = pd.read_csv("nba.csv"
      
data.dropna(inplace = True)
   
# creating DataFrame form weight column
gfg = pd.DataFrame(data['Weight'].head())
   
# using to_numpy()
print(type(gfg.to_numpy()))

chevron_right


Output:

<class 'numpy.ndarray'>



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.