在熊猫中舍入到最近的1000

问题描述 投票:2回答:4

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

你如何用更大的数字做到这一点?

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

df.SalesPrice.WhatDoIDo(1000)? 
python pandas data-science
4个回答
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
投票

你可以试试这个

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

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.