Pandas custom rounding given a list of values

You can use the function cut:

df = pd.Series([11,16,21, 125])

rounding_logic = pd.Series([15, 20, 100])
labels = rounding_logic.tolist()
rounding_logic = pd.Series([-np.inf]).append(rounding_logic) # add infinity as leftmost edge

pd.cut(df, rounding_logic, labels=labels).fillna(rounding_logic.iloc[-1])
# get bins, assign labels and fill all values that greater than 100 with 100

Output:

0     15
1     20
2    100
3    100
dtype: category
Categories (3, int64): [15 < 20 < 100]

 

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top