import data from an excel file, if no values write "nan" in python

To import data from an excel file and replace missing values with "nan" using Python, you can use the pandas package. Here's an example code block that demonstrates how to do this:

main.py
import pandas as pd

df = pd.read_excel('path/to/file.xlsx', na_values='')

# replace empty cells with nan
df.fillna(value='nan', inplace=True)

print(df)
155 chars
9 lines

In this code block, we first import the pandas package and then use the read_excel() function to read the excel file located at "path/to/file.xlsx". The na_values parameter is used to specify what values should be interpreted as missing values. In this case, we set it to an empty string ''.

After reading the file, we use the fillna() method to replace all empty cells with the string "nan". The inplace=True parameter ensures that the changes are made directly to the original dataframe.

Finally, we print out the resulting dataframe which should now have all missing values replaced with "nan".

gistlibby LogSnag