1
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8') 

filtered_data['Receita Total'] = filtered_data['Receita Total'].apply(lambda x: locale.currency(x, grouping=True))

filtered_data['Margem Final'] = filtered_data['Margem Final'].apply(lambda x: f"{x:.2f}%")

How can I format my columns as currency without them ending up in object/string format? I want them to be numeric so that I can sort the numbers from highest to lowest without them being in alphabetical order.

My table has this format

print(filtered_data.dtypes)
row.names         object
data              object
ano              float64
razaoSocial       object
cnpj              object
entidadeId        object
status_final      object
total_exames       int64
receita_total    float64
margem_final     float64

When I format the column it changes to object, but I don't want that to happen

filtered_data['receita_total'] = filtered_data['receita_total'].apply(lambda x: locale.currency(x, grouping=True))

filtered_data['margem_final'] = filtered_data['margem_final'].apply(lambda x: f"{x:.2f}%")

print(filtered_data.dtypes)
row.names         object
data              object
ano              float64
razaoSocial       object
cnpj              object
entidadeId        object
status_final      object
total_exames       int64
receita_total     object
margem_final      object
dtype: object
3
  • Does this answer your question? How to display pandas DataFrame of floats using a format string for columns? Commented Apr 10, 2024 at 11:51
  • Especially answer stackoverflow.com/a/46370761/987358 should help. Commented Apr 10, 2024 at 11:53
  • As the links in the comments above indicate, you need to leave integers and floating point numbers as is, then use locale based formatting via styles when displayed or printed. In someways its lucky you are using locale.format_currency() which is the only way to get thousands separators on bsd libc derived implementations. Not sure whether it will work on musl libc based systems. Commented Apr 11, 2024 at 6:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.