DataFrame.groupby.sample: Get a Random Sample of Items from Each Category in a Column

DataFrame.groupby.sample: Get a Random Sample of Items from Each Category in a Column

If you want to get a random sample of items from each category in a column, use df.groupby.sample. To get 2 items from each category, use n=2.

This method is useful when you want to get a subset of a DataFrame while keeping all categories in a column.

Link to the source code.

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran