You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Float对象进行四舍五入?解决Pandas计算百分比保留一位小数时的AttributeError问题

解决Python Float对象无法调用.round()的问题

嘿,这个问题我之前也碰到过!咱们来一步步理清楚:

为什么会报错?

你得到的计算结果是Python原生的float类型,而.round()是Pandas专属的方法(只适用于Series、DataFrame这类Pandas数据结构),所以直接给float用这个方法肯定会触发AttributeError。

三种可行的解决方案

1. 使用Python内置的round()函数

这是最简单直接的方式,直接把你的计算结果作为第一个参数传入,第二个参数指定保留的小数位数:

round(
    df.loc[((df['education-num'] < 13)|(df['education'] == 'Prof-school')) & (df['salary'] == '>50K')].shape[0] 
    / df.loc[(df['education-num'] < 13)| (df['education'] == 'Prof-school')].shape[0] * 100,
    1
)

执行后会返回17.4这个float类型的结果。

2. 使用NumPy的np.round()

如果你已经在项目里用到了NumPy,也可以用它的round方法,效果和内置函数一致:

import numpy as np

np.round(
    df.loc[((df['education-num'] < 13)|(df['education'] == 'Prof-school')) & (df['salary'] == '>50K')].shape[0] 
    / df.loc[(df['education-num'] < 13)| (df['education'] == 'Prof-school')].shape[0] * 100,
    1
)

3. 字符串格式化(适合展示输出)

如果你的需求是把结果以保留一位小数的形式打印或展示,字符串格式化会更灵活:

# 先计算出原始百分比
percentage = df.loc[((df['education-num'] < 13)|(df['education'] == 'Prof-school')) & (df['salary'] == '>50K')].shape[0] / df.loc[(df['education-num'] < 13)| (df['education'] == 'Prof-school')].shape[0] * 100

# 两种格式化方式任选其一
print("{:.1f}".format(percentage))
# 或者更简洁的f-string写法
print(f"{percentage:.1f}")

这样会输出字符串形式的17.4,适合直接展示给用户。

内容的提问来源于stack exchange,提问作者Andrew Hobson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:17:38