2017-04-14 64 views
0

我有熊猫系列,如:大熊猫据帧四舍五入一系列

tempDF['A'] = dfOld.cl 

其中.CL是一个字符串:

23.340000 
24.350000 
...... 

我想将它转换为浮动,然后轮至2位

tempDF['A'] = round(dfOld.cl.astype(float),2) 

输出应该是:

23.34 
24.35 
..... 

这样做的最好方法是什么?

+2

做,当你运行你所提供的代码,你会得到什么,“tempDF [ 'A'] = ROUND(dfOld.cl.astype(浮动) ,2)“?该代码看起来正确。 –

回答

1

可以使用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 
+0

顺便说一句,如果你使用'jupyter-notebook',你可以键入'df.cl. '得到一个弹出列表,列出绑定到'Series'的所有方法,并且可以运行一个包含命令'dfOld.cl.round?'的单元来查看方法签名。 – kjfl