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.
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):
