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.
import pandas as pd
data = pd.read_csv( "nba.csv" )
data.dropna(inplace = True )
gfg = pd.Series(data[ 'Weight' ].head())
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.
import pandas as pd
data = pd.read_csv( "nba.csv" )
data.dropna(inplace = True )
gfg = pd.Series(data[ 'Weight' ].head())
print (gfg.to_numpy(dtype = 'float32' ))
|
Output :
[180. 235. 185. 235. 238.]
Code #3 : Validating the type of the array after conversion.
import pandas as pd
data = pd.read_csv( "nba.csv" )
data.dropna(inplace = True )
gfg = pd.Series(data[ 'Weight' ].head())
print ( type (gfg.to_numpy()))
|
Output :
<class 'numpy.ndarray'>
Last Updated :
27 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...