【问题标题】:How to rounds a given number up to the nearest specified multiple using Pandas?如何使用 Pandas 将给定数字四舍五入到最接近的指定倍数?
【发布时间】:2020-10-14 07:55:03
【问题描述】:

我想知道是否有内置的 Pandas 模块可以将给定的数字四舍五入到最接近的指定倍数。

在 excel 中,这可以使用 Ceiling function 来实现。

假设 df 为 -0.4, 0.5,1.5,然后将其四舍五入为 1 的倍数将得到 0,1,and 2

虽然我已经在网上梳理了这个话题,但我没有看到任何关于它的参考资料。如果这是重复的,请告诉我。

其他人可能会建议类似 here 但它不是内置的 Pandas

【问题讨论】:

  • np.ceil(df)np.ceil(serie)

标签: python pandas


【解决方案1】:

也许是这个?

> import math as m
> [m.ceil(n) for n in [-0.4, 0.5, 1.5]]
[0, 1, 2]

有数据框

> import pandas as pd
> df = pd.DataFrame([-0.4, 0.5, 1.5], columns=['numbers'])
> df.apply(m.ceil, axis=1)
0    0
1    1
2    2
dtype: int64

然后没有apply

> import numpy as np
> np.ceil(df['numbers'])
0   -0.0
1    1.0
2    2.0
Name: numbers, dtype: float64

其实你也可以通过运算得到类似的结果。

> df // 1 + 1
    numbers
0   0.0
1   1.0
2   2.0

【讨论】:

  • 感谢您的建议,但 OP 以数据框的形式呈现数据。
  • 似乎外部模块仍然需要。
  • @balandongiv,也许不是,我添加了一个没有外部模块的。
  • 为此加一个,也许这回答了为什么没有内置函数。
【解决方案2】:

我认为这是 here 的回答,不是专门针对 pandas,而是针对 numpy,尽管我认为这是您正在寻找的行为。

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 2011-03-25
    • 2012-03-07
    • 2011-03-16
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多