Pandas Dataframe.to_numpy() – Convert dataframe to Numpy array
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)
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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 pandasimport pandas as pd # reading the csv data = pd.read_csv("nba.csv") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # using to_numpy() functionprint(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 pandasimport pandas as pd # read csv file data = pd.read_csv("nba.csv") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # providing dtypeprint(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 columngfg = pd.DataFrame(data['Weight'].head()) # using to_numpy()print(type(gfg.to_numpy())) |
Output:
<class 'numpy.ndarray'>


