Разделить фрейм данных Pandas по значению столбца

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

Иногда для более точного анализа Dataframe нам необходимо разделить его на 2 или более частей. Pandas предоставляет функцию разделения Dataframe в соответствии с индексом столбца, индексом строки, значениями столбца и т. Д.

Давайте посмотрим, как разделить фрейм данных Pandas по значению столбца в Python?

Now, let’s create a Dataframe:

Python3

# importing pandas library
import pandas as pd
  
# Initializing the nested list with Data-set
player_list = [["M.S.Dhoni", 36, 75, 5428000],
               ["A.B.D Villers", 38, 74, 3428000],
               ["V.Kholi", 31, 70, 8428000],
               ["S.Smith", 34, 80, 4428000],
               ["C.Gayle", 40, 100, 4528000],
               ["J.Root", 33, 72, 7028000],
               ["K.Peterson", 42, 85, 2528000]]
  
# creating a pandas dataframe
df = pd.DataFrame(player_list, 
                  columns = ["Name", "Age"
                             "Weight", "Salary"])
  
# show the dataframe
df

Выход:

Метод 1: использование логического маскирования подход.

Этот метод используется для печати только той части фрейма данных, в которой мы передаем логическое значение True.

Example 1:

Python3

# importing pandas library
import pandas as pd
  
# Initializing the nested list with Data-set
player_list = [["M.S.Dhoni", 36, 75, 5428000],
               ["A.B.D Villers", 38, 74, 3428000],
               ["V.Kholi", 31, 70, 8428000],
               ["S.Smith", 34, 80, 4428000],
               ["C.Gayle", 40, 100, 4528000],
               ["J.Root", 33, 72, 7028000],
               ["K.Peterson", 42, 85, 2528000]]
  
# creating a pandas dataframe
df = pd.DataFrame(player_list, 
                  columns = ["Name", "Age"
                             "Weight", "Salary"])
  
# splitting the dataframe into 2 parts
# on basis of "Age" column values
# using Relational operator
df1 = df[df["Age"] >= 37]
  
# printing df1
df1

Выход:

Python3



df2 = df[df["Age"] < 37]
  
# printing df2
df2

Output:

In the above example, the data frame ‘df’ is split into 2 parts ‘df1’ and ‘df2’ on the basis of values of column ‘Age‘.

Example 2: 

Python3

# importing pandas library
import pandas as pd
  
# Initializing the nested list with Data-set
player_list = [["M.S.Dhoni", 36, 75, 5428000],
               ["A.B.D Villers", 38, 74, 3428000],
               ["V.Kholi", 31, 70, 8428000],
               ["S.Smith", 34, 80, 4428000],
               ["C.Gayle", 40, 100, 4528000],
               ["J.Root", 33, 72, 7028000],
               ["K.Peterson", 42, 85, 2528000]]
  
# creating a pandas dataframe
df = pd.DataFrame(player_list, 
                  columns = ["Name", "Age"
                             "Weight", "Salary"])
  
# splitting the dataframe into 2 parts
# on basis of "Weight" column values
mask = df["Weight"] >= 80
  
df1 = df[mask]
  
# invert the boolean values
df2 = df[~mask]
  
# printing df1
df1

Output:


Python3

# printing df2
df2

Output:

In the above example, the data frame ‘df’ is split into 2 parts ‘df1’ and ‘df2’ on the basis of values of column ‘Weight‘.

Method 2: Using Dataframe.groupby().

This method is used to split the data into groups based on some criteria.

Example:

Python3

# importing pandas library
import pandas as pd
  
# Initializing the nested list with Data-set
player_list = [["M.S.Dhoni", 36, 75, 5428000],
               ["A.B.D Villers", 38, 74, 3428000],
               ["V.Kholi", 31, 70, 8428000],
               ["S.Smith", 34, 80, 4428000],
               ["C.Gayle", 40, 100, 4528000],
               ["J.Root", 33, 72, 7028000],
               ["K.Peterson", 42, 85, 2528000]]
  
# creating a pandas dataframe
df = pd.DataFrame(player_list, 
                  columns = ["Name", "Age"
                             "Weight", "Salary"])
  
# splitting the dataframe into 2 parts
# on basis of "Salary" column values
# using dataframe.groupby() function
df1, df2 = [x for _, x in df.groupby(df["Salary"] < 4528000)]
  
# printing df1
df1

Output:


Python3

# printing df2
df2

Выход:

В приведенном выше примере фрейм данных «df» разделен на 2 части «df1» и «df2» на основе значений столбца « Salary ».

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

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