Python Forum

Full Version: Formatting issues?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here's some code:
format_mapping2 = {'ES_Cum_%ROI':'{:.2%}','Port_Cum_%ROI':'{:.2%}','Port_Marg_Tot':'{:.2f}'}
for key, value in format_mapping2.items():
    comp_df[key] = comp_df[key].apply(value.format)
print(comp_df)
comp_df = comp_df.apply(pd.to_numeric)
print(comp_df.dtypes)
ES_mean = comp_df.iloc[:,0].mean()
With lines 1-3, comp_df prints with the formatting I want.

I then want to do further processing, though... like get mean, std, min/max, etc. When I include the last line, I get: ValueError: Unable to parse string "276.50%" at position 0 . If I take out line 5, then I get TypeError: Could not convert 272.31%165.15% to numeric (that's why I tried WITH line 5).

So--when I format these columns as percentages, am I actually changing them to strings (with or without lines 1-3, dtypes show up as "object" for all columns)? And if they are strings, how to I change them back to numeric so I can proceed with the further processing? Thanks!
This works:
ES_mean = comp_df.iloc[:,0].mean(); print('ES_Cum_%ROI mean is {:.2%}'.format(ES_mean))
Port_mean = comp_df.iloc[:,1].mean(); print('Port_Cum_%ROI mean is {:.2%}'.format(Port_mean))
ES_worst = comp_df.iloc[:,0].min(); Port_worst = comp_df.iloc[:,1].min()
ES_std = comp_df.iloc[:,0].std(); Port_std = comp_df.iloc[:,1].std()
print('ES worst = {:.2%}'.format(ES_worst)); print('Port worst = {:.2%}'.format(Port_worst))
holder = comp_df.agg({'ES_Cum_%ROI':['mean', 'std'], 'Port_Cum_%ROI':['mean','std']}) #computing agg before formatting to %
format_mapping2 = {'ES_Cum_%ROI':'{:.2%}','Port_Cum_%ROI':'{:.2%}','Port_Marg_Tot':'{:.2f}'}
for key, value in format_mapping2.items():
    comp_df[key] = comp_df[key].apply(value.format)
print(comp_df)
pd.options.display.float_format = '{:.2%}'.format
print(holder)
Because I couldn't process after formatting, I had to add line 6 and call it in line 12. I also had to format twice: lines 7-9 and 11.

Is there an easier way or is this how it must be done?