[Python] How to flatten nested lists using pandas groupby

Discussão em 'Python' iniciado por Stack, Abril 30, 2025.

  1. Stack

    Stack Membro Participativo

    My pandas DataFrame has a column with lists dtype. I'd like to Group By and aggregate the DataFrame and flatten the lists.

    Here's a sample DataFrame:

    import pandas as pd

    df = pd.DataFrame({
    'id': [1, 1, 2],
    'cat': ['A','A','B'],
    'lst': [['l0','l1','l2'],['l3','l4'],['lb']],
    'v': [10, 20, 10]
    })


    Use mean to aggregate column v.

    Expected output:

    id cat lst v

    1 A ['l0','l1','l2','l3','l4'] 15
    2 B ['lb'] 10

    Continue reading...

Compartilhe esta Página