I discretized a column in my dataframe using pandas.cut with bins created by IntervalIndex.from_tuples.
The cut works as intended however the categories are shown as the tuples I specified in the IntervalIndex. Is there any way to rename the categories into a different label e.g. (Small, Medium, Large)?
Example:
bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])
pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)
The resulting categories will be:
[NaN, (0, 1], NaN, (2, 3], (4, 5]]
Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]
I am trying to change [(0, 1] < (2, 3] < (4, 5]] into something like 1, 2 ,3 or small, medium ,large.
Sadly, the labels parameter arguments of pd.cut is ignored when using IntervalIndex.
Thanks!
UPDATE:
Thanks to @SergeyBushmanov I noticed that this issue only exist when trying to change category labels inside a dataframe (which is what I am trying to do). Updated example:
In [1]: df = pd.DataFrame([0, 0.5, 1.5, 2.5, 4.5], columns = ['col1'])
In [2]: bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])
In [3]: df['col1'] = pd.cut(df['col1'], bins)
In [4]: df['col1'].categories = ['small','med','large']
In [5]: df['col1']
Out [5]:
0 NaN
1 (0, 1]
2 NaN
3 (2, 3]
4 (4, 5]
Name: col1, dtype: category
Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]

所有评论(0)