I'm rounding a column from my dataframe to the nearest 5 floating point. After that I'm converting the column values into string, but when I do that the float go back as if they were unrounded. I'm using 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
Here I think you can use string formatting. I use '${:,.2f}'.format(1234.5)
(source here) for formatting dollars and cents, but I was able to use the same formatting method in a lambda function for your float to string.
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))
First do the rounding using your function
df['A'] = df['kl'].apply(lambda x: custom_round(x, base=.05))
Now, you can use python
's string formatting to round your floats
df['b'] = df['A'].apply(lambda x: 'D = ' + '{:.5f}'.format(x))
I am not sure if this is valid for python 2.7
, if not you can try
df['b'] = df['A'].apply(lambda x: 'D = ' + '%.5f' % (x,))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With