Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add plus sign for positive number when using to_excel?

This is my DataFrame.

import pandas as pd 
import numpy as np
df = pd.DataFrame(
    {
        'a': [2, 2, 2, -4, np.nan, np.nan, 4, -3, 2, -2, -6],
        'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6]
    }
)

I want to add a plus sign for positive numbers only for column a when exporting to Excel. For example 1 becomes +1. Note that I have NaN values as well. I want them to be empty cells in Excel similar to the default behavior of Pandas when dealing with NaN values in to_excel.

I have tried many solutions. This is one of them. But it didn’t work in Excel.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df.style.format({'a': '{:+g}'}).to_excel(r'df.xlsx', sheet_name='xx', index=False)

>Solution :

What about using a callable:

(df.style.format({'a': lambda x: f'{x:+g}' if np.isfinite(x) else ''})
   .to_excel(r'/tmp/df.xlsx', sheet_name='xx', index=False)
)

Alternative callable: lambda x: '' if np.isnan(x) else f'{x:+g}'

Output (in jupyter):

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading