add age categories pandas dataframe

X_train_data = pd.DataFrame({'Age':[0,2,4,13,35,-1,54]})

bins= [0,2,4,13,20,110]
labels = ['Infant','Toddler','Kid','Teen','Adult']
X_train_data['AgeGroup'] = pd.cut(X_train_data['Age'], bins=bins, labels=labels, right=False)
print (X_train_data)
   Age AgeGroup
0    0   Infant
1    2  Toddler
2    4      Kid
3   13     Teen
4   35    Adult
5   -1      NaN
6   54    Adult

Here is what the above code is Doing:
1. We created a DataFrame with a column named ‘Age’ and a column named ‘AgeGroup’.
2. We created a list of bins and a list of labels.
3. We used the pd.cut() function to cut the ‘Age’ column into bins and assign labels to each bin.
4. We created a new column named ‘AgeGroup’ and assigned the labels to the corresponding bins.

Note that the -1 value in the ‘Age’ column was assigned to the NaN label.

Let’s look at another example.