熊猫数据框四舍五入

时间:2017-04-14 18:31:52

标签: python pandas jupyter-notebook

我有一个熊猫系列,如:

tempDF['A'] = dfOld.cl

其中.cl是一个字符串:

23.340000
24.350000
......

我想把它转换成一个浮点数,然后转到2个地方

tempDF['A'] = round(dfOld.cl.astype(float),2)
输出应该是:

23.34
24.35
.....

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用pandas.Series.round功能来完成此任务:

In [1]: import pandas as pd

In [2]: dfOld = pd.DataFrame({'cl': ['0.014', '0.015', '0.016']})
dfOld.cl.apply(type).value_counts()  # prove that the values are strings

Out[2]:
<type 'str'>    3
dtype: int64

In [3]:
dfOld.cl.astype(float).round(decimals=2)

Out[3]:
0    0.01
1    0.02
2    0.02
Name: cl, dtype: float64