pandas 四舍五入到最近的“n" [英] Pandas round to the nearest "n"

查看:72
本文介绍了 pandas 四舍五入到最近的“n"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数字系列有一个很好的四舍五入方法,可以四舍五入到十的幂,例如

<预><代码>>>>pd.Series([11,16,21]).round(-1)0 101 202 20数据类型:int64

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

解决方案

您可以使用自定义舍入函数和 apply 将它应用到您的系列中.

将pandas导入为pddef custom_round(x, base=5):返回 int(base * round(float(x)/base))df = pd.Series([11,16,21]).apply(lambda x: custom_round(x, base=5))

现在您只需要调整 base 以获得您想要的最接近的值.

几个例子:

基数 = 5:

0 101 152 20数据类型:int64

基数 = 7

0 141 142 21数据类型:int64

基数 = 3

0 121 152 21数据类型:int64

<小时>

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

def custom_round(x, base=5):返回基数 * 轮(浮动(x)/基数)df = pd.Series([11.35,16.91,21.12]).apply(lambda x: custom_round(x, base=.05))

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

0 11.351 16.902 21.10数据类型:float64

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

Numeric series have a nice rounding method for rounding to powers of ten, eg

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

Is there an equivalently nice syntax for rounding to the nearest 5 (or other non-power of 10)? I'm sort of wishing that round could take non-integer values?

解决方案

You can utilize a custom rounding function and apply it to your series.

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))

Now you just need to adjust the base to get to the nearest value you want.

A couple examples:

Base = 5:

0    10
1    15
2    20
dtype: int64

Base = 7

0    14
1    14
2    21
dtype: int64

Base = 3

0    12
1    15
2    21
dtype: int64


Your goal of non-integer values can be done too.

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))

By rounding to the nearest 0.05, you'll get these results (notice I modified your series slightly for this example):

0    11.35
1    16.90
2    21.10
dtype: float64

If you keep your original series of integers, this apply will change your series into float values:

这篇关于 pandas 四舍五入到最近的“n"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆