Search code examples
pythonpandasdataframeexport-to-csvfillna

why is df.fillna() only filling some rows and the first column


Trying to fill all empty spots rows and columns with [], however fillna() will only do some rows and the first column. My code has worked in previous runs so I'm not sure what happened.

    df = df.fillna(value = "[]")
    print(df[['keywords']])
    df.to_csv(r'C:\Users\user\dfexport.csv', index=False, header=True)

When looking at the csv file it looks like:export.csv

The print statement looks like:print(df[['keywords]])


Solution

  • import pandas as pd
    import numpy as np
     
    # initialize list of lists
    data = [['tom', 10], ['',''], []]
    # Create the pandas DataFrame
    df = pd.DataFrame(data, columns = ['Name', 'Age'])
    df.replace('', np.nan, inplace=True)
    df = df.fillna(value = "[]")
    print(df)