Python Forum

Full Version: Can I format decimal places by column with a dictionary?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here's some code:
markets = {'ES':2, 'GC':1, 'CL':2, 'EC':4, 'US':4}
merge_list = [] 
pd.options.display.float_format = '{:.2f}'.format

for market in markets:
    columnname_0 = market+'_Close'
    columnname_1 = market+'_Daily_Rtn'
    columnname_2 = market+'_Cum_Rtn'
    columnname_3 = market+'_Value'
    df_name = market
    market = pd.read_csv(r'C:\Users\drkle\{}(daily).csv'.format(market), parse_dates=["Date"], index_col="Date")
    merge_list.append(market_cut)

merged_df = pd.concat(merge_list, axis=1)
I've since realized I don't want two decimal places for all columns. I changed Line 1 from a list to dictionary with values equal to the desired number of decimal places (in column 0 for each component dataframe). I found this line on SO:
market_cut[df_name] = market_cut[df_name].map('{:,.2f}'.format)
How might I build that out to call the values of markets to format accordingly (e.g. 'ES_Close' column to two decimal places, 'GC_Close' column to one decimal place, 'EC_Close' to four decimal places, etc.)? Alternatively, can you think of another way to do this? Thanks!
This works:
format_mapping = {markets[0]+'_Close':'{:.2f}',markets[1]+'_Close':'{:.1f}',markets[2]+'_Close':'{:.2f}', markets[3]+'_Close':'{:.4f}', markets[4]+'_Close':'{:.4f}'}
for key, value in format_mapping.items():
    merged_df[key] = merged_df[key].apply(value.format)
I did a lot of reading on df.style.format. This did not work:
format_dict = {markets[0]+'_Close':'{:.2f}',markets[1]+'_Close':'{:.1f}',markets[2]+'_Close':'{:.2f}', markets[3]+'_Close':'{:.4f}', markets[4]+'_Close':'{:.4f}'}
merged_df.style.format(format_dict) 
Does anyone know what might be wrong with that? No Traceback... just nothing happened.
This works:
format_mapping = {markets[0]+'_Close':'{:.2f}',markets[1]+'_Close':'{:.1f}',markets[2]+'_Close':'{:.2f}', markets[3]+'_Close':'{:.4f}', markets[4]+'_Close':'{:.4f}'}
for key, value in format_mapping.items():
    merged_df[key] = merged_df[key].apply(value.format)
I did a lot of reading about df.style.format . I don't understand why this did not work:
format_dict = {markets[0]+'_Close':'{:.2f}',markets[1]+'_Close':'{:.1f}',markets[2]+'_Close':'{:.2f}', markets[3]+'_Close':'{:.4f}', markets[4]+'_Close':'{:.4f}'}
merged_df.style.format(format_dict) #WHY DID THIS NOT WORK?
I didn't get a Traceback. I just didn't see any formatting occur. Does it have to do with printing a df rather than a table?
Did I have to do something else to print out the Styler object (which did seem to be there when I typed merged_df.style and/or merged_df.style.format)?

I'm using Python 3.7.9.