基于0.45阈值的定价舍入问题:期望basePrice为355却得355.357
问题解决
你的代码存在两个核心问题:
- 数据结构错误:把
testdata定义成嵌套列表,却用类似pandas DataFrame的列名方式赋值,列表不支持字符串索引,会直接报错。 - 舍入函数逻辑冗余:
round_Pricing里的if (x > 0) else判断完全多余,两个分支的条件完全一致。
修正后的代码
import pandas as pd # 正确定义为pandas DataFrame testdata = pd.DataFrame([[317, 1.21]], columns=['itemnumberPrice', 'Markup']) # 计算basePrice testdata['basePrice'] = testdata['itemnumberPrice'] * testdata['Markup'] def round_Pricing(x): # 分离整数部分i和小数部分f i, f = divmod(x, 1) # 正数小数部分>=0.45则进一位,否则保留原整数部分 return int(i + 1) if f >= 0.45 else int(i) # 应用舍入函数 testdata['roundedPrice'] = testdata['basePrice'].apply(round_Pricing) print(testdata)
说明
- 先将数据转为pandas DataFrame,才能使用列名索引和
apply方法。 - 修正后的
round_Pricing逻辑直接:仅判断小数部分是否≥0.45,是则整数部分加1,否则保留原整数部分,完全满足你“不依赖整数奇偶性、仅按小数阈值舍入”的需求。 - 示例:若
basePrice为355.357,小数部分0.357<0.45,舍入后得到355;若为355.45,小数部分≥0.45,舍入后得到356。
内容的提问来源于stack exchange,提问作者Slade
相关产品推荐
相关产品推荐

