【发布时间】:2016-11-02 03:29:51
【问题描述】:
数值系列有一个很好的四舍五入方法,用于四舍五入到十的幂,例如
>>> pd.Series([11,16,21]).round(-1)
0 10
1 20
2 20
dtype: int64
是否有一个相当好的语法来四舍五入到最接近的 5(或其他非 10 的幂)?我有点希望round 可以采用非整数值?
【问题讨论】:
数值系列有一个很好的四舍五入方法,用于四舍五入到十的幂,例如
>>> pd.Series([11,16,21]).round(-1)
0 10
1 20
2 20
dtype: int64
是否有一个相当好的语法来四舍五入到最接近的 5(或其他非 10 的幂)?我有点希望round 可以采用非整数值?
【问题讨论】:
您可以使用自定义舍入函数并将其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 即可获得您想要的最接近的值。
几个例子:
0 10
1 15
2 20
dtype: int64
0 14
1 14
2 21
dtype: int64
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 值:
【讨论】:
df['B'] = "A = " + df['C'].astype(str) 当我尝试将列设为字符串时会发生这种情况
其中一个答案建议使用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
【讨论】:
我想我可以这样做:
def round_down_to_nearest(self, n):
return (self // n) * n
pd.Series.round_down_to_nearest = round_down_to_nearest
【讨论】: