Pandas Groupby dos columnas

Suraj Joshi 30 enero 2023
  1. Pandas Groupby Múltiples Columnas
  2. Contar el número de filas en cada grupo Pandas
Pandas Groupby dos columnas

Este tutorial explica cómo podemos utilizar el método DataFrame.groupby() en Pandas para dos columnas para separar el DataFrame en grupos. También podemos obtener mucha más información de los grupos creados.

En este artículo utilizaremos el siguiente DataFrame.

import pandas as pd

roll_no = [501, 502, 503, 504, 505]

data = pd.DataFrame(
    {
        "Name": ["Jennifer", "Travis", "Bob", "Emma", "Luna", "Anish"],
        "Gender": ["Female", "Male", "Male", "Female", "Female", "Male"],
        "Employed": ["Yes", "No", "Yes", "No", "Yes", "No"],
        "Age": [30, 28, 27, 24, 28, 25],
    }
)

print(data)

Producción :

       Name  Gender Employed  Age
0  Jennifer  Female      Yes   30
1    Travis    Male       No   28
2       Bob    Male      Yes   27
3      Emma  Female       No   24
4      Luna  Female      Yes   28
5     Anish    Male       No   25

Pandas Groupby Múltiples Columnas

import pandas as pd

roll_no = [501, 502, 503, 504, 505]

data = pd.DataFrame(
    {
        "Name": ["Jennifer", "Travis", "Bob", "Emma", "Luna", "Anish"],
        "Gender": ["Female", "Male", "Male", "Female", "Female", "Male"],
        "Employed": ["Yes", "No", "Yes", "No", "Yes", "No"],
        "Age": [30, 28, 27, 24, 28, 25],
    }
)

print(data)
print("")
print("Groups in DataFrame:")
groups = data.groupby(["Gender", "Employed"])
for group_key, group_value in groups:
    group = groups.get_group(group_key)
    print(group)
    print("")

Resultado:

       Name  Gender Employed  Age
0  Jennifer  Female      Yes   30
1    Travis    Male       No   28
2       Bob    Male      Yes   27
3      Emma  Female       No   24
4      Luna  Female      Yes   28
5     Anish    Male       No   25

Groups in DataFrame:
   Name  Gender Employed  Age
3  Emma  Female       No   24

       Name  Gender Employed  Age
0  Jennifer  Female      Yes   30
4      Luna  Female      Yes   28

     Name Gender Employed  Age
1  Travis   Male       No   28
5   Anish   Male       No   25

  Name Gender Employed  Age
2  Bob   Male      Yes   27

Crea 4 grupos a partir del DataFrame. Todas las filas con el mismo valor de la columna Gender y Employed se colocan en el mismo grupo.

Contar el número de filas en cada grupo Pandas

Para contar el número de filas de cada grupo creado con el método DataFrame.groupby(), podemos utilizar el método size().

import pandas as pd

roll_no = [501, 502, 503, 504, 505]

data = pd.DataFrame(
    {
        "Name": ["Jennifer", "Travis", "Bob", "Emma", "Luna", "Anish"],
        "Gender": ["Female", "Male", "Male", "Female", "Female", "Male"],
        "Employed": ["Yes", "No", "Yes", "No", "Yes", "No"],
        "Age": [30, 28, 27, 24, 28, 25],
    }
)

print(data)
print("")
print("Count of Each group:")
grouped_df = data.groupby(["Gender", "Employed"]).size().reset_index(name="Count")
print(grouped_df)

Producción :

       Name  Gender Employed  Age
0  Jennifer  Female      Yes   30
1    Travis    Male       No   28
2       Bob    Male      Yes   27
3      Emma  Female       No   24
4      Luna  Female      Yes   28
5     Anish    Male       No   25

Count of Each group:
   Gender Employed  Count
0  Female       No      1
1  Female      Yes      2
2    Male       No      2
3    Male      Yes      1

Muestra el DataFrame, los grupos creados a partir del DataFrame, y el número de entradas en cada grupo.

Si queremos el mayor valor de recuento para cada valor de la columna Employed, podemos formar otro grupo a partir del grupo creado anteriormente y contar los valores y luego obtener el valor máximo de recuento utilizando el método max().

import pandas as pd

roll_no = [501, 502, 503, 504, 505]

data = pd.DataFrame(
    {
        "Name": ["Jennifer", "Travis", "Bob", "Emma", "Luna", "Anish"],
        "Gender": ["Female", "Male", "Male", "Female", "Female", "Male"],
        "Employed": ["Yes", "No", "Yes", "No", "Yes", "No"],
        "Age": [30, 28, 27, 24, 28, 25],
    }
)

print(data)
print("")

groups = data.groupby(["Gender", "Employed"]).size().groupby(level=1)
print(groups.max())

Resultado:

       Name  Gender Employed  Age
0  Jennifer  Female      Yes   30
1    Travis    Male       No   28
2       Bob    Male      Yes   27
3      Emma  Female       No   24
4      Luna  Female      Yes   28
5     Anish    Male       No   25

Employed
No     2
Yes    2
dtype: int64

Muestra el recuento máximo de valores de la columna Employed entre los grupos creados de las columnas Gender y Employed.

Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

Artículo relacionado - Pandas DataFrame Column

Artículo relacionado - Pandas Groupby