Home > database >  How to fill result file with not presented columns names?
How to fill result file with not presented columns names?

Time:05-25

I write the result output datafrate to file:

for key, columns in formats.items():
  output.to_csv('c:/temp/' filenameshort '_shopformat_' key '.csv', columns=columns, encoding='utf-8', sep="|", index=False, header=False)

Where formats is:

formats = {
    "kids": ['NUM', 'MMYY', 'FIRSTNAME', 'ADDRESS', 'EMAIL']
}

Problem is that dataframe output does not have all columns that are in formats.kids. It gives me an error:

KeyError: "['ADDRESS'] not in index"

How to create file with all columns from formats.kids?

The output has:

NUM AGE MMYY

Result should be:

 NUM AGE MMYY FIRSTNAME ADDRESS EMAIL
 1    18  1212

CodePudding user response:

IIUYC, you want to add null columns to your df, you can try:

for key, columns in formats.items():
    for col in columns:
        if col not in output.columns:
            output[col]=np.nan
    output.to_csv('c:/temp/' filenameshort '_shopformat_' key '.csv', columns=columns, encoding='utf-8', sep="|", index=False, header=False)
  • Related