pandas 熊猫四舍五入到最近的“n”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40372030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas round to the nearest "n"
提问by maxymoo
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?
是否有同样好的语法可以四舍五入到最接近的 5(或其他非 10 的幂)?我有点希望round
可以采用非整数值?
回答by Andy
You can utilize a custom rounding function and apply
it to your series.
您可以使用自定义舍入函数并将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))
Now you just need to adjust the base
to get to the nearest value you want.
现在您只需要调整base
以获得您想要的最接近的值。
A couple examples:
几个例子:
Base = 5:
基数 = 5:
0 10
1 15
2 20
dtype: int64
Base = 7
基数 = 7
0 14
1 14
2 21
dtype: int64
Base = 3
基数 = 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.05,您将得到以下结果(注意我在此示例中稍微修改了您的系列):
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:
如果您保留原始整数系列,这apply
会将您的系列更改为float
值:
回答by maxymoo
I guess I could do this:
我想我可以这样做:
def round_down_to_nearest(self, n):
return (self // n) * n
pd.Series.round_down_to_nearest = round_down_to_nearest