Pandas Dataframe.to_numpy () - Преобразование фрейма данных в массив Numpy

Опубликовано: 27 Марта, 2022

Pandas DataFrame - это двумерная потенциально неоднородная структура табличных данных с изменяемым размером и помеченными осями (строки и столбцы). Эта структура данных может быть преобразована в NumPy ndarray с помощью метода Dataframe.to_numpy () .

Syntax: Dataframe.to_numpy(dtype = None, copy = False)

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

Чтобы получить ссылку на файл csv, щелкните 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 pandas
import pandas as pd 
   
# reading the csv  
data = pd.read_csv("nba.csv"
      
data.dropna(inplace = True)
   
# creating DataFrame form weight column
gfg = pd.DataFrame(data["Weight"].head())
   
# using to_numpy() function
print(gfg.to_numpy())

Выход:

 [[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 pandas
import pandas as pd 
   
# read csv file  
data = pd.read_csv("nba.csv"
      
data.dropna(inplace = True)
   
# creating DataFrame form weight column
gfg = pd.DataFrame(data["Weight"].head())
   
# providing dtype
print(gfg.to_numpy(dtype ="float32"))

Выход:

 [[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 column
gfg = pd.DataFrame(data["Weight"].head())
   
# using to_numpy()
print(type(gfg.to_numpy()))

Выход:

 <класс 'numpy.ndarray'>

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.