Open In App

Python | Pandas Series.to_numpy()

Improve
Improve
Like Article
Like
Save
Share
Report

Pandas Series.to_numpy() function is used to return a NumPy ndarray representing the values in given Series or Index.

This function will explain how we can convert the pandas Series to numpy Array. Although it’s very simple, but the concept behind this technique is very unique. Because we know the Series having index in the output. Whereas in numpy arrays we only have elements in the numpy arrays.

Syntax: Series.to_numpy()

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.

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

Code #1 :

Changing the Series into numpy array by using a method Series.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 series form weight column
gfg = pd.Series(data['Weight'].head())
  
# using to_numpy() function
print(type(gfg.to_numpy()))


Output :

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

 
Code #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 series form weight column
gfg = pd.Series(data['Weight'].head())
  
# providing dtype
print(gfg.to_numpy(dtype ='float32'))


Output :

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

 
Code #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 series form weight column
gfg = pd.Series(data['Weight'].head())
  
# using to_numpy()
print(type(gfg.to_numpy()))


Output :

<class 'numpy.ndarray'>


Last Updated : 27 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads