Related Articles

Related Articles

Python | Pandas Series.to_numpy()
  • Last Updated : 27 Feb, 2019

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :