Home > Enterprise >  Pandas - Append CSV file with incomplete columns
Pandas - Append CSV file with incomplete columns

Time:11-04

I have a CSV file with three columns: col1, col2, col3 I'm trying to append to this file a DataFrame containing only the col2

ds = {'col2':[20]}
df = pd.DataFrame(ds)
df.to_csv(csi_filepath,mode='a',index=False,header=False)

the result is:

col1 col2 col3
20 NaN NaN

I would expect:

col1 col2 col3
NaN 20 NaN

Is it possible to achieve this somehow?

CodePudding user response:

Try with reindex

ds = {'col2':[20]}
df = pd.DataFrame(ds).reindex(columns = ['col1','col2','col3'])
df.to_csv(csi_filepath,mode='a',index=False,header=False)
  • Related