Python Pandas 中的自定义舍入函数问题

问题描述 投票:0回答:1

我已经使用 Pandas 在 Python 中实现了自定义舍入函数,但在某些情况下它没有产生预期的结果。它基本上应该总是向下舍入到最近的步骤。这是该函数以及我如何应用它:

import pandas as pd

# Define the custom rounding function
def custom_round(x, step):
    return x if round(x / step) * step == x else (x // step) * step

# Sample DataFrame similar to my data structure
data = {
    "1": [1.300, 1.400, 1.333, 1.364, 1.400],
    "X": [5.0, 5.0, 5.0, 4.5, 4.5]
}

outcome = pd.DataFrame(data)

# Define the step for rounding
step = 0.1

# Apply custom_round to create new columns
outcome["1_cluster"] = outcome["1"].apply(lambda x: custom_round(x, step))
outcome["X_cluster"] = outcome["X"].apply(lambda x: custom_round(x, step))

print(outcome)

我从这个脚本得到的输出是:

      1    X  1_cluster  X_cluster
0  1.300  5.0        1.3        5.0
1  1.400  5.0        1.3        5.0
2  1.333  5.0        1.3        5.0
3  1.364  4.5        1.3        4.5
4  1.400  4.5        1.3        4.5

但是,1_cluster 和 X_cluster 的正确输出应该是:

      1    X  1_cluster  X_cluster
0  1.300  5.0        1.3        5.0
1  1.400  5.0        1.4        5.0
2  1.333  5.0        1.3        5.0
3  1.364  4.5        1.3        4.5
4  1.400  4.5        1.4        4.5

函数 custom_round 似乎正确舍入为 5.0 或 4.5,但未能正确舍入为 1.4。如何修改 custom_round 以确保它也正确舍入为 1.4?

我很感激任何见解或建议。谢谢!

python pandas dataframe numpy scikit-learn
1个回答
0
投票

这是一个自定义舍入解决方案,通过查找使步长成为整数所需的小数点移动数字

n
,将步长和值的小数部分乘以
10**n
,执行整数除法得到小数点后的步骤块的数量,最后将仅步骤块的数字重新组合为小数。

def custom_round(x, step):
    if step >= 1:
        raise ValueError('Step must be less than 1')
    n = 0
    new_step = step
    if step < 1:
        while (new_step % 10 != 0):
            n += 1
            new_step = new_step * 10
    m = 10 ** n
    new_step = int(step * m)
    x_whole, x_frac = divmod(x, 1)
    new_x_frac = x_frac * m
    chunks = int(new_x_frac // new_step)
    return x_whole + (chunks * new_step / m)
© www.soinside.com 2019 - 2024. All rights reserved.