Python | Pandas Series.to_numpy()

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.

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

chevron_right


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.

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

chevron_right


Output :

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

 
Code #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 series form weight column
gfg = pd.Series(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.