Pandas to_excel formatting float values
Question:
I’m exporting a dataframe to an excel file using to_excel from pandas but I need that all the number values (float64) to be formatted (without specifing each columns because that will be variable) as a string (BRL currency) when exported.
import pandas as pd
df = pd.DataFrame({'Numero': {0: '044121', 1: '044121'}, 'Serie': {0: '0', 1: '0'}, 'Finalidade': {0: '1', 1: '1'},
'CNPJ_CPF_Emit': {0: '01039778000177', 1: '01039778000177'},
'Rz_Emit': {0: 'VINHEDOS INDUSTRIA E COMERCIO DE PAPEIS LTDA.', 1: 'VINHEDOS INDUSTRIA E COMERCIO DE PAPEIS LTDA.'},
'PIS_Valor': {0: 1620.98, 1: 1210.42}, 'COFINS_Valor': {0: 7466.32, 1: 5575.28}, 'Valor_IPI': {0: 3628.22, 1: 2709.28},
'Valor_ICMS': {0: 13396.5, 1: 10003.5},
'Valor_Total_Nota': {0: 201337.5, 1: 201337.5}, 'Valor_Frete': {0: '', 1: ''}})
df.to_excel(my_path, index=False, freeze_panes=(1,0))
resulting in:
and the desired excel output would be:
Is it possible? If so, how is the better way to do it?
Can be done using the float_format parameter when writing the excel?
Thanks!
Answers:
Before saving
def format_currency(value):
if pd.isna(value):
return ''
return 'R$ {:.2f}'.format(value)
#For saving in Brl
for col in df.select_dtypes(include=['float64']).columns:
df[col] = df[col].apply(format_currency)
This should do the trick. You need just place in between the df declaration and saving it
It’s possible to customize the format if you install xlsxwriter
(with another code, it can work with openpyxl
too).
# pip install xlsxwriter
with pd.ExcelWriter('output.xlsx', engine='xlsxwriter') as writer:
# write the dataframe before modify the sheet
df.to_excel(writer, sheet_name='Sheet1')
wb = writer.book # get workbook
ws = writer.sheets['Sheet1'] # and worksheet
# add a new format then apply it on right columns
currency_fmt = wb.add_format({'num_format': 'R$ #,###.##'})
ws.set_column('F:J', None, currency_fmt)
Output:
I’ve used both answers and came up with this to solve my problem:
with pd.ExcelWriter(my_path, engine="xlsxwriter") as writer:
df.to_excel(writer, index=False, freeze_panes=(1,0), sheet_name="export")
wb = writer.book
ws = writer.sheets["export"]
formato_moeda = wb.add_format({'num_format': 'R$ #.###,##'})
for col in df.select_dtypes(include=['float64']).columns:
col = df.columns.get_loc(col)
ws.set_column(col, col, None, formato_moeda)
Thanks Corralien and Arunbh Yashaswi for the help!
I’m exporting a dataframe to an excel file using to_excel from pandas but I need that all the number values (float64) to be formatted (without specifing each columns because that will be variable) as a string (BRL currency) when exported.
import pandas as pd
df = pd.DataFrame({'Numero': {0: '044121', 1: '044121'}, 'Serie': {0: '0', 1: '0'}, 'Finalidade': {0: '1', 1: '1'},
'CNPJ_CPF_Emit': {0: '01039778000177', 1: '01039778000177'},
'Rz_Emit': {0: 'VINHEDOS INDUSTRIA E COMERCIO DE PAPEIS LTDA.', 1: 'VINHEDOS INDUSTRIA E COMERCIO DE PAPEIS LTDA.'},
'PIS_Valor': {0: 1620.98, 1: 1210.42}, 'COFINS_Valor': {0: 7466.32, 1: 5575.28}, 'Valor_IPI': {0: 3628.22, 1: 2709.28},
'Valor_ICMS': {0: 13396.5, 1: 10003.5},
'Valor_Total_Nota': {0: 201337.5, 1: 201337.5}, 'Valor_Frete': {0: '', 1: ''}})
df.to_excel(my_path, index=False, freeze_panes=(1,0))
resulting in:
and the desired excel output would be:
Is it possible? If so, how is the better way to do it?
Can be done using the float_format parameter when writing the excel?
Thanks!
Before saving
def format_currency(value):
if pd.isna(value):
return ''
return 'R$ {:.2f}'.format(value)
#For saving in Brl
for col in df.select_dtypes(include=['float64']).columns:
df[col] = df[col].apply(format_currency)
This should do the trick. You need just place in between the df declaration and saving it
It’s possible to customize the format if you install xlsxwriter
(with another code, it can work with openpyxl
too).
# pip install xlsxwriter
with pd.ExcelWriter('output.xlsx', engine='xlsxwriter') as writer:
# write the dataframe before modify the sheet
df.to_excel(writer, sheet_name='Sheet1')
wb = writer.book # get workbook
ws = writer.sheets['Sheet1'] # and worksheet
# add a new format then apply it on right columns
currency_fmt = wb.add_format({'num_format': 'R$ #,###.##'})
ws.set_column('F:J', None, currency_fmt)
Output:
I’ve used both answers and came up with this to solve my problem:
with pd.ExcelWriter(my_path, engine="xlsxwriter") as writer:
df.to_excel(writer, index=False, freeze_panes=(1,0), sheet_name="export")
wb = writer.book
ws = writer.sheets["export"]
formato_moeda = wb.add_format({'num_format': 'R$ #.###,##'})
for col in df.select_dtypes(include=['float64']).columns:
col = df.columns.get_loc(col)
ws.set_column(col, col, None, formato_moeda)
Thanks Corralien and Arunbh Yashaswi for the help!