用熊猫取整数字



我有一个pandas数据帧,其中有一列包含数字:[4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01,...]

我想把这一列四舍五入到小数点后的3位,为此我使用了round(col(函数;然而,我注意到熊猫给了我以下信息:[0.453, 0.658, 1.349, 20.692, 0.35,...]其中最后一个元素在小数后没有三位数字。

我希望所有的数字都用相同数量的数字四舍五入,例如:[0.453, 0.658, 1.349, 20.692, 0.350,...]

如何在熊猫体内做到这一点?

您可以使用pandas.DataFrame.round来指定精度。

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html

import pandas as pd
# instantiate dataframe
dataframe = pd.DataFrame({'column_to_round': [4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01,]})
# create a new column with this new precision
dataframe['set_decimal_level'] = dataframe.round({'column_to_round': 3})

import pandas as pd    
df = pd.DataFrame([4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01], columns=['numbers'])
df.round(3)

打印:

0.453 0.658 1.349 20.692 0.350

最新更新