在熊猫中舍入到最近的1000

时间:2017-12-23 01:35:34

标签: python pandas data-science

我搜索了pandas文档和食谱配方,很明显你可以使用dataframe.columnName.round(decimalplace)轻松地舍入到最接近的小数位。

你如何使用更大的数字?

例如,我有一列房价,我希望它们四舍五入到最接近的10000或1000或其他什么。

df.SalesPrice.WhatDoIDo(1000)? 

5 个答案:

答案 0 :(得分:3)

使用符号df.ColumnName.round(),您实际上正在调用pandas.Series.round,其文档指定:

  

小数:int

     

要舍入的小数位数(默认值:0)。如果小数为负数,则指定小数点左侧的位置数。

所以你可以这样做:

df = pd.DataFrame({'val':[1,11,130,670]})
df.val.round(decimals=-2)

这会产生输出:

0      0
1      0
2    100
3    700
Name: val, dtype: int64

decimals=-3轮到1000s,依此类推。值得注意的是,它也可以使用pandas.DataFrame.round(),虽然文档没有告诉你:

df = pd.DataFrame({'val':[1,11,130,670], 'x':[1,11,150,900]})
df.round({'val':-2})

这会将列val四舍五入到最接近的100,但只留下x

答案 1 :(得分:1)

你可以试试这个

df = pd.DataFrame({'val':[1,11,130,670]})
10**df.val.astype(str).str.len()
Out[27]: 
0      10
1     100
2    1000
3    1000
Name: val, dtype: int64

答案 2 :(得分:0)

对于要在小数点左侧指定精度的情况,函数round确实接受负值:

dataframe.columnName.round(-3)

示例:

>>> pd.Series([1, 500, 500.1, 999, 1500, 1501, 946546]).round(-3)
0         0.0
1         0.0
2      1000.0
3      1000.0
4      2000.0
5      2000.0
6    947000.0
dtype: float64

答案 3 :(得分:0)

另一个有趣的“黑客”是这样的:假设你要四舍五入到最近的100。您可以添加50,然后除以100,转换为整数,再乘以100。

df = pd.DataFrame({'val':[1005,1299,1301,4109]})
df.val.round(-2) # Proper way
((df.val+50)/100).astype(int)*100 # Hack

根据需要给你这个:

[1000, 1300, 1300, 4100]

答案 4 :(得分:0)

我最喜欢的动态方式:

<块引用>

ds:pd.Series 到“圆形”
x: 四舍五入的整数/浮点数

# Define rounding lambda function:
my_rounder = lambda ds, x: ((ds + 0.5*10**x) // 10**x) * 10**x

# Apply lambda function to "prices" values:
housing_df["rounded_prices"] = my_rounder(housing_df["prices"], 3)

# If you need to force/ensure no decimal:
housing_df["rounded_prices"] = housing_df["rounded_prices"].apply(int)

替代地板圆角:

my_floor_rounder = lambda ds, x: (ds // 10**x) * 10**x

细分:

print(housing_df["prices"].head())

year
2010    372560.0
2011    374507.0
2012    376454.0
2013    378401.0
2014    380348.0
Name: prices, dtype: float64
    
# This step can be omitted if you're finding the floor:
step_up = housing_df["prices"] + 0.5*10**3
print(step_up.head())

year
2010    373060.0
2011    375007.0
2012    376954.0
2013    378901.0
2014    380848.0
Name: prices, dtype: float64

thsnd = step_up // 10**3
print(thsnd.head())

year
2010    373.0
2011    375.0
2012    376.0
2013    378.0
2014    380.0
Name: prices, dtype: float64

rounded = thsnd * 10**3
print(rounded.head())

year
2010    373000.0
2011    375000.0
2012    376000.0
2013    378000.0
2014    380000.0
Name: prices, dtype: float64

int_rounded = rounded.apply(int)
print(int_rounded.head())

year
2010    373000
2011    375000
2012    376000
2013    378000
2014    380000
Name: prices, dtype: int64