Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 27 Feb, 2020

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.




# 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())

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.




# 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'))

Output:

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

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




# 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()))

Output:

<class 'numpy.ndarray'>

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!