Quantcast
Viewing latest article 1
Browse Latest Browse All 3

Answer by Panda Kim for Bining a set of numbers in a specific way

Example

import pandas as pds = pd.Series(range(1000, 2004)).div(10)

s:

0       100.01       100.12       100.23       100.34       100.4        ...  999     199.91000    200.0 <-- exactly 2001001    200.11002    200.21003    200.3Length: 1004, dtype: float64

Code

How about additionally processing the case where value is exactly 200 with boolean masking in the result of the pd.cut function?

bins=[100, 135, 160, 175, 190, 200]labels=['[100, 135)', '[135, 160)', '[160, 175)', '[175, 190)', '[190, 200]']cond = s.eq(200)out = pd.cut(s, bins=bins, labels=labels, right=False).mask(cond, '[190, 200]')

out:

0       [100, 135)1       [100, 135)2       [100, 135)3       [100, 135)4       [100, 135)           ...    999     [190, 200]1000    [190, 200] <-- exactly 2001001           NaN1002           NaN1003           NaNLength: 1004, dtype: categoryCategories (5, object): ['[100, 135)'< '[135, 160)'< '[160, 175)'< '[175, 190)'< '[190, 200]']

Viewing latest article 1
Browse Latest Browse All 3

Trending Articles