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

Python Pandas如何仅对索引结尾为指定字符串的行做零位小数舍入?

Pandas 实现方案

核心逻辑如下:

  • 通过索引的str.endswith('_sum')方法构造布尔掩码,定位所有符合后缀要求的行
  • 用loc索引器单独修改目标行的number列数值,仅对这部分执行舍入操作,其余行的数值精度完全保留

完整可运行代码示例

import pandas as pd

# 1、构造和你需求一致的测试DataFrame
data = {"number": [500.000, 0.509, 0.342]}
index_list = ["acb_sum", "deff", "ghi"]
df = pd.DataFrame(data, index=index_list)
df.index.name = "col1" # 给索引设置名称为col1,和你的示例对齐

# 2、核心处理逻辑
# 构造筛选掩码
sum_row_mask = df.index.str.endswith("_sum")
# 对目标行的number列做0位小数舍入
df.loc[sum_row_mask, "number"] = df.loc[sum_row_mask, "number"].round(0)

# 【可选操作】如果你需要_sum结尾的数值显示为整数而非500.0的浮点数格式,增加这行类型转换
df.loc[sum_row_mask, "number"] = df.loc[sum_row_mask, "number"].astype(int)

注意事项

如果你的DataFrame索引不是字符串格式,需要先执行df.index = df.index.astype(str)转换为字符串类型,否则str.endswith()方法会报错。
如果不想修改原始DataFrame,可以先执行new_df = df.copy(),再对new_df做上述处理即可。

处理后输出df即可得到你预期的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 20:21:03