四舍五入到最接近的1000只Pandas

2024-09-27 22:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经搜索了pandas文档和食谱,很明显您可以使用dataframe.columnName.round(decimalplace)轻松地四舍五入到最接近的小数点。在

对于较大的数字,如何处理?在

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

df.SalesPrice.WhatDoIDo(1000)? 

Tags: 文档dataframepandasdf数字食谱小数点round
3条回答

如果要指定小数点左边的精度,函数round不接受负值:

dataframe.columnName.round(-3)

示例:

^{pr2}$

通过使用符号df.ColumnName.round(),实际上是在调用^{},其文档指定:

decimals : int

Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

所以你可以:

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

这将产生输出:

^{pr2}$

decimals=-3循环到1000,依此类推。值得注意的是,它也可以使用pandas.DataFrame.round(),尽管文档没有告诉您:

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

这将把val列四舍五入到最接近的100,但不要使用x。在

你可以试试这个

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

相关问题 更多 >

    热门问题