Разделить фрейм данных Pandas по индексу столбца
Pandas поддерживает две структуры данных для хранения данных: ряд (один столбец) и фрейм данных, где значения хранятся в 2D-таблице (строки и столбцы). Чтобы проиндексировать фрейм данных с помощью индекса, нам нужно использовать метод dataframe.iloc (), который принимает
Syntax: pandas.DataFrame.iloc[]
Parameters:
Index Position: Index position of rows in integer or list of integer.Return type: Data frame or Series depending on parameters
Let’s create a dataframe. In the below example we will use a simple binary dataset used to classify if a species is a mammal or reptile. The species column holds the labels where 1 stands for mammal and 0 for reptile. The data is stored in the dict which can be passed to the DataFrame function outputting a dataframe.
Python3
import pandas as pd dataset = {"toothed": [1, 1, 1, 0, 1, 1, 1, 1, 1, 0], "hair": [1, 1, 0, 1, 1, 1, 0, 0, 1, 0], "breathes": [1, 1, 1, 1, 1, 1, 0, 1, 1, 1], "legs": [1, 1, 0, 1, 1, 1, 0, 0, 1, 1], "species": [1, 1, 0, 1, 1, 1, 0, 0, 1, 0] } df = pd.DataFrame(dataset) df.head() |
Выход :

вывод головы ()
Пример 1: Теперь мы хотели бы отделить столбцы видов от столбцов характеристик (зубчатые, волосы, дыхание, ноги), для этого мы собираемся использовать метод iloc [rows, columns], предлагаемый pandas.
Here ‘:’ stands for all the rows and -1 stands for the last column so the below cell is going to take the all the rows and all columns except the last one (‘species’) as can be seen in the output:
Python3
X = df.iloc[:,:-1]X |
Выход:

To split the species column from the rest of the dataset we make you of a similar code except in the cols position instead of padding a slice we pass in an integer value -1.
Python3
Y = df.iloc[:,-1]Y |
Выход :

Пример 2: Разделение с использованием списка целых чисел
Similar output can be obtained by passing in a list of integers instead of a slice
Python3
X = df.iloc[:,[0,1,2,3]]X |
Выход:

To the species column we are going to use the index of the column which is 4 we can use -1 as well
Python3
Y = df.iloc[:,4]Y |
Выход:

Пример 3: Разделение фреймов данных на 2 отдельных фрейма данных
В приведенных выше двух примерах выходными данными для Y была серия, а не фрейм данных. Теперь мы собираемся разделить фрейм данных на два отдельных фрейма данных, это может быть полезно при работе с наборами данных с несколькими метками. Будет использоваться тот же набор данных.
In the first, we are going to split at column hair
Python3
df.iloc[:,[0,1]] |
Выход:

The second dataframe will contain 3 columns breathes , legs , species
Python3
df.iloc[:,[2,3,4]] |
Выход:

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