将舍入的float转换为string pandas的问题

时间:2018-06-29 14:36:19

标签: python-2.7 pandas dataframe floating-point rounding

我正在将数据框中的列四舍五入到最接近的5个浮点。之后,我将列值转换为字符串,但是当我这样做时,浮点数会像未取整一样返回。我正在使用Python 2.7

import pandas as pd
df=pd.read_excel(C:"path")

def custom_round(x, base=5):
    return base * round(float(x)/base)

df['A'] = df['kl'].apply(lambda x: custom_round(x, base=.05))
df['b'] = "D = "  + df['A'].astype(str)


     kl     A                       b  
 0.600001  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600000  0.60  D = 0.6000000000000001  
 0.600000  0.60  D = 0.6000000000000001  
 0.600587  0.60  D = 0.6000000000000001  
 0.601573  0.60  D = 0.6000000000000001  
 0.601168  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600000  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.600001  0.60  D = 0.6000000000000001  
 0.850001  0.85  D = 0.8500000000000001  

2 个答案:

答案 0 :(得分:1)

在这里,我认为您可以使用字符串格式。我使用'${:,.2f}'.format(1234.5)(源here)来格式化美元和美分,但是我能够在lambda函数中使用相同的格式化方法来将浮点数转换为字符串。

import pandas as pd 
data = {'kl' : [0.600001, 0.600001, 0.600000, 0.600000, 
                0.600587, 0.601573, 0.601168, 0.600001, 
                0.600001, 0.600001, 0.600000, 0.600001, 
                0.600001, 0.600001, 0.600001, 0.850001]}
df = pd.DataFrame.from_dict(data)

def custom_round(x, base=5):
    return base * round(float(x)/base)

df['A'] = df['kl'].apply(lambda x: custom_round(x, base=.05))
df['b'] = "D = " + df['A'].apply(lambda s: '{:,.5f}'.format(s))

答案 1 :(得分:0)

首先使用您的函数进行四舍五入

df['A'] = df['kl'].apply(lambda x: custom_round(x, base=.05))

现在,您可以使用python的字符串格式来四舍五入

df['b'] =  df['A'].apply(lambda x:  'D = ' + '{:.5f}'.format(x))

我不确定这对python 2.7是否有效,如果不能,您可以尝试

df['b'] = df['A'].apply(lambda x:  'D = ' + '%.5f' % (x,))