python - 在 pandas 中舍入一个范围

我有 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

我想对范围进行四舍五入以绘制它并使比例看起来不错。

我试过 df_surf_dist.index.round(decimals=-1)

但我得到了 AttributeError: 'RangeIndex' object has no attribute 'round'

我也试过 df_surf_dist.index = df_surf_dist.index.to_series().apply(lambda x: x.round(1))

但我得到了 AttributeError: 'int' object has no attribute 'round'

回答1

您可以使用自定义函数重新创建间隔:

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)

输出:

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

使用的输入:

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)

相似文章

最新文章