Reputation: 95
I am attempting to convert a DataFrame of Floats, to Strings, while keeping trailing zeros at the hundredth decimal point. Here is my function:
def df_formatter(df):
cols = df.columns
for x in cols:
for index,cell in enumerate(df[x]):
df.loc[:,x][index] = str('{:.2f}'.format(Decimal(df[x][index])))
return df
The issue is that my dataframe is still in float format, even after applying the function. when i apply .astype(str) method to convert to strings, I lose the hundredth decimal point, if that hundredth decimal is a 0. For example, 0.00 --> 0.0, or 0.50 --> 0.5. This is currency and percentage data, so important to keep trailing zeros.
What is my issue?
Upvotes: 1
Views: 3363
Reputation: 561
I am not sure if i understood correctly but I think this is a solution:
df = pd.DataFrame({'floats': [0.5, 0.66, 0.]})
df['floats'] = df['floats'].apply(lambda x: "{:.2f}".format(x))
print(df)
>>>
floats
0 0.50
1 0.66
2 0.00
Upvotes: 5