【问题标题】:Pandas round to the nearest "n"熊猫四舍五入到最近的“n”
【发布时间】:2016-11-02 03:29:51
【问题描述】:

数值系列有一个很好的四舍五入方法,用于四舍五入到十的幂,例如

>>> pd.Series([11,16,21]).round(-1)
0    10
1    20
2    20
dtype: int64

是否有一个相当好的语法来四舍五入到最接近的 5(或其他非 10 的幂)?我有点希望round 可以采用非整数值?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用自定义舍入函数并将其apply 用于您的系列。

    import pandas as pd
    
    def custom_round(x, base=5):
        return int(base * round(float(x)/base))
    
    df = pd.Series([11,16,21]).apply(lambda x: custom_round(x, base=5))
    

    现在您只需调整base 即可获得您想要的最接近的值。

    几个例子:

    基数 = 5:

    0    10
    1    15
    2    20
    dtype: int64
    

    基数 = 7

    0    14
    1    14
    2    21
    dtype: int64
    

    基数 = 3

    0    12
    1    15
    2    21
    dtype: int64
    

    您也可以实现非整数值的目标。

    def custom_round(x, base=5):
        return base * round(float(x)/base)
    
    df = pd.Series([11.35,16.91,21.12]).apply(lambda x: custom_round(x, base=.05))
    

    通过四舍五入到最接近的 0.05,您将得到以下结果(请注意,我在此示例中稍微修改了您的系列):

    0    11.35
    1    16.90
    2    21.10
    dtype: float64
    

    如果您保留原来的整数系列,则此 apply 会将您的系列更改为 float 值:

    【讨论】:

    • 当浮点数以零结尾时不显示第二个数字,例如 0.6 我怎样才能让它显示 0.60? df['B'] = "A = " + df['C'].astype(str) 当我尝试将列设为字符串时会发生这种情况
    【解决方案2】:

    其中一个答案建议使用apply 传递lambda,该lambda 除以10,将其四舍五入为最接近的整数,然后乘以10。相反,您可以通过执行以下操作来利用pandas 中的矢量化以下:

    >>> s = pd.Series([11, 16, 21])
    >>> (s / 10).round().astype(int) * 10
    0    10
    1    20
    2    20
    dtype: int64
    

    【讨论】:

      【解决方案3】:

      我想我可以这样做:

      def round_down_to_nearest(self, n):
          return (self // n) * n
      
      pd.Series.round_down_to_nearest = round_down_to_nearest
      

      【讨论】:

      • 这是向下取整,而不是四舍五入(19 将变为 15 而不是 20)。
      • @kennytm 好点...我将重命名函数(因为这实际上是我想要的)
      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2020-04-24
      相关资源
      最近更新 更多