Home > Net >  Round a range in pandas
Round a range in pandas

Time:05-18

I have df_surf_dist=

                 index  surface_relle_bati
0      (8.718, 27.733]                 442
1     (27.733, 46.467]                1485
2       (46.467, 65.2]                1296
3       (65.2, 83.933]                 927
4    (83.933, 102.667]                 288
5     (102.667, 121.4]                  81
6     (121.4, 140.133]                  22
7   (140.133, 158.867]                   8
8     (158.867, 177.6]                  10
9     (177.6, 196.333]                   1
10  (196.333, 215.067]                   1
11    (215.067, 233.8]                   1
12    (233.8, 252.533]                   0
13  (252.533, 271.267]                   0
14    (271.267, 290.0]                   1

I want to round the range in order to plot it and make the scale look nice.

I tried df_surf_dist.index.round(decimals=-1)

but I got AttributeError: 'RangeIndex' object has no attribute 'round'

I also tried df_surf_dist.index = df_surf_dist.index.to_series().apply(lambda x: x.round(1))

but I got AttributeError: 'int' object has no attribute 'round'

CodePudding user response:

You can use a custom function to recreate the intervals:

def round_interval(i, ndigits=2):
    return pd.Interval(round(i.left, ndigits), round(i.right, ndigits), i.closed)

df['range'].apply(round_interval, ndigits=1)

output:

0     (8.7, 27.7]
1    (27.7, 46.5]
2    (46.5, 65.2]
Name: range, dtype: interval

used input:

from pandas import Interval
d = {'range': {0: Interval(8.718, 27.733, closed='right'),
               1: Interval(27.733, 46.467, closed='right'),
               2: Interval(46.467, 65.2, closed='right')},
     'surface_relle_bati': {0: 442, 1: 1485, 2: 1296}}
df = pd.DataFrame(d)

CodePudding user response:

Instead of x.round() could you try round(x) and check if it's working?

  • Related