I have a DataFrame like:
df = pd.DataFrame([1,2,1,3,4,5], columns=['data'])
and a set of categories and bounds:
catBounds = pd.DataFrame([['a',1,2],
['b',3,4]],
columns=['cat','lb','ub'])
that I would like to add a column of categories to the first DataFrame where if the value lies between bounds 1 and 2, the new column is assigned "a" and if the value lies between the bounds 3 and 4, the new column is assigned "b". An inelegant way of doing this would be to loop over the rows of catBounds and making assignments:
for index, row in catBounds.iterrows():
df.loc[(df.data>=row.lb) & (df.data<=row.ub), 'cat'] = row['cat']
getting:
| data | cat | |
|---|---|---|
| 0 | 1 | a |
| 1 | 2 | a |
| 2 | 1 | a |
| 3 | 3 | b |
| 4 | 4 | b |
| 5 | 5 | NaN |
Is there a cleaner, more Pythonic way of doing this?