[Python] Sampling a pandas DataFrame and balance data across group

Discussão em 'Python' iniciado por Stack, Agosto 7, 2025.

  1. Stack

    Stack Membro Participativo

    Trying to figure out how to use pandas.DataFrame.sample or any other function to balance this data:

    Given this DataFrame:

    d = {'class':['c1','c2','c1','c1','c2','c1','c1','c2','c3','c3'],
    'val': [1,2,1,1,2,1,1,2,3,3]
    }
    df = pd.DataFrame(d)


    I would like to extract a sample that is balanced across the group class, that is, we should fix the class, and extract the same number of observations for each class.

    In particular, I would like the per-class number of observations to equal the sample size of the smallest class.

    UPDATE


    piRSquared's answer works but:

    How g.apply(lambda x: x.sample(g.size().min())) works? I know what 'lambda` is, but:

    • What is passed to lambda in x in this case?
    • What is g in g.size()?
    • Why output contains 6,5,4, 1,8,9 numbers? What do they mean?

    Continue reading...

Compartilhe esta Página