Handle Nan when using Pandas ExcelWriter in python

Mike picture Mike · Feb 24, 2016 · Viewed 13.1k times · Source

How would I change the following code to handle NaN values as just empty cells within my dataframe as I iterate through it line by line outputting values in column A?

excel = pd.ExcelWriter(f_name,engine='xlsxwriter')
wb = excel.book
ws = wb.add_worksheet('PnL')

for i in len(df):
  ws.write(0,i,df.iloc[i]['A'])

Answer

jezrael picture jezrael · Feb 24, 2016

I think you can use fillna:

df = df.fillna(0)

or:

df['A'] = df['A'].fillna(0)

But better is use to_excel:

import pandas as pd
import numpy as np

# Create a Pandas dataframe from the data.
df = pd.DataFrame({'A': [10, 20, 30, 20, 15, 30, 45, np.nan], 
                   'B': [10, 20, 30, 20, 15, 30, 45, np.nan]})
print df
    A   B
0  10  10
1  20  20
2  30  30
3  20  20
4  15  15
5  30  30
6  45  45
7 NaN NaN

#create subset, because cannot write Series to excel
df1 = df[['A']]

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('f_name.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object, instead NaN give 0
df1.to_excel(writer, sheet_name='PnL', na_rep=0)

If you want omit index and header, add parameters index=False and header=False:

df1.to_excel(writer, sheet_name='PnL', na_rep=0, index=False, header=False)

excel