If you have a DataFrame containing a column of numeric values, you can use the value_counts() function with bins to group the values into specific ranges.
Let’s illustrate this by creating a DataFrame with ages and then using the value_counts() function to create 3 groups.
ages = [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70] ages_df = pd.DataFrame(ages, columns=['Age']) ages_df['Age'].value_counts(bins=3)
(19.948999999999998, 36.667] 4
(53.333, 70.0] 4
(36.667, 53.333] 3
You can also use the value_counts() function with a list of bin edges to create custom bins. For example, if you want to group the ages into three bins, you can use the following code:
ages_df['Age'].value_counts(bins=[20, 40, 60, 80])
(19.999, 40.0] 5
(40.0, 60.0] 4
(60.0, 80.0] 2