0

I would like to export a dataframe to Excel as xls and show numbers with a 1000 separator and 2 decimal places and percentages as % with 2 decimals, e.g. 54356 as 54,356.00 and 0.0345 as 3.45%

When I change the format in python using .map() and .format it displays them correctly in python, but it turns them into a string and when I export them to xls Excel does not recognize them as numbers/percentages.

import pandas as pd

d = {'Percent': [0.01, 0.0345], 'Number': [54464.43, 54356]}
df = pd.DataFrame(data=d)

df['Percent'] = pd.Series(["{0:.2f}%".format(val * 100) for val in df['Percent']], index = df.index)

df['Number'] = df['Number'].map('{:,.2f}'.format)

The data frame looks as expected, but the type of the cells is now str and if I export it to xls (df.to_excel('file.xls')), Excel shows the "The number in this cell is formatted as text or preceded by an apostrophe" warning.

2
  • Not an answer to your question but percent has its own formatting code. df.Percent.map('{:.2%}'.format)
    – piRSquared
    Jul 17, 2019 at 14:35
  • When writing to excel you can specify float_format. Sadly, this is one format for all columns, and doesn't accept a dict of {col: format_str}, so it's not a perfect solution, given you need the % sign.
    – ALollz
    Jul 17, 2019 at 15:06

4 Answers 4

0

You can edit the style property when you display the DataFrame, but the underlying data is not touched

df.style.format({
    'Number': '{0:.2f}'.format, 
    'Percent': '{0:.2%}'.format,
})

see: pandas style guide

0

If I understand your question correctly, your goal is the way how the actual cells in the output excel file are formatted. To do this, you may want to focus on the actual file rather than formatting within pandas DataFrame (i.e. your data is correct, the problem is the way they're displayed in the output).

You may want to try something like this.

0

maybe lambda would be more helpful

df['Percent'] = df['Percent'].apply(lambda x: round(x*100, 2))
df['Number'] = df['Number'].apply(lambda x: round(x, 2))
0
  • For df["Number"] : df.Number = df.Number.apply(lambda x : '{0:,.2f}'.format(x)) will work

  • For df["Percent"] : first multiply the series by 100. df["Percent"] = df.Percent.multiply(100)

    • Then use df.Percent = df.Percent.apply(lambda x: "{0:.2f}%".format(x))

Hope this helps

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.