将计算列四舍五入为 1dp

我知道这是一个流行的查询,但我在这里没有找到任何与我需要的完全匹配的东西。我在表格中有一列将 36.25 舍入为 36.2 而不是 36.3。在这里广泛阅读了这篇文章后,我很欣赏这些细节,但这并不能帮助我解决我的问题。我怎样才能创建一些代码来围绕我的“结果”列,如我所愿?此代码生成我正在使用的 df 版本:


import pandas as pd

import numpy as np


raw_data = {'AreaCode' : ['101', '102', '103', '104'],

            'Numerator' : [300, 500, 600, 667],

            'Denominator' : [1000, 780, 1100, 1840]}

Data = pd.DataFrame(raw_data, columns = ['AreaCode', 'Numerator', 'Denominator'])

然后我试图添加一个“结果”列:


Data['Outcome'] = Data['Numerator'] / Data['Denominator'] * 100

生成下表:


AreaCode|Numerator|Denominator|Outcome

101|300|1000|30.000000 

102|500|780|64.102564 

103|600|1100|54.545455

104|667|1840|36.25000

这很好,除非我申请Data = Data.round(1)这个,它将 36.250000 舍入到 36.2。我需要将此列显示为 36.3,但如何在 Python 中对此进行编码。此处有关如何执行此操作的示例使用一次性的、用户输入的数字字符串,而不是整个 df.column。它不会让我将我的 df.column 传递给这些。我试过的一个例子不起作用:


import math

def my_round(n, ndigits):

    part = n * 10 ** ndigits

    delta = part - int(part)

    # always round "away from 0"

    if delta >= 0.5 or -0.5 < delta <= 0:

        part = math.ceil(part)

    else:

        part = math.floor(part)

    return part / (10 ** ndigits


繁华开满天机
浏览 113回答 2
2回答

慕标琳琳

我对您的功能做了一些调整,现在它似乎可以工作了:)def my_round(n, ndigits=1):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp;part = n * 10 ** ndigits&nbsp; &nbsp; &nbsp; &nbsp;delta = part - int(part)&nbsp; &nbsp; &nbsp; &nbsp;# always round "away from 0"&nbsp; &nbsp; &nbsp; &nbsp;if delta >= 0.5 or -0.5 < delta <= 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;part = math.ceil(part)&nbsp; &nbsp; &nbsp; &nbsp;else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;part = math.floor(part)&nbsp; &nbsp; &nbsp; &nbsp;val =&nbsp; part/(10 ** ndigits)&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp;val = np.nan&nbsp; &nbsp; return valData['Outcome'] = (Data['Numerator'].divide(Data['Denominator'])*100).apply(my_round)print(Data)输出:&nbsp; AreaCode&nbsp; Numerator&nbsp; Denominator&nbsp; Outcome0&nbsp; &nbsp; &nbsp; 101&nbsp; &nbsp; &nbsp; &nbsp; 300&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1000&nbsp; &nbsp; &nbsp;30.01&nbsp; &nbsp; &nbsp; 102&nbsp; &nbsp; &nbsp; &nbsp; 500&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 780&nbsp; &nbsp; &nbsp;64.12&nbsp; &nbsp; &nbsp; 103&nbsp; &nbsp; &nbsp; &nbsp; 600&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1100&nbsp; &nbsp; &nbsp;54.53&nbsp; &nbsp; &nbsp; 104&nbsp; &nbsp; &nbsp; &nbsp; 667&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1840&nbsp; &nbsp; &nbsp;36.3

白衣非少年

将 pandas 导入笔记本后,您可以添加此行,以便您的浮点值不会超过小数点后一位:import pandas as pdpd.options.display.float_format = '{:.1f}'.format
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python