Skip to content Skip to sidebar Skip to footer

Skip First Rows When Writing Csv (pandas.dataframe.to_csv)

In my python script I am reading a csv file via df = pd.read_csv('input.csv', sep=';', encoding = 'ISO-8859-1', skiprows=2, skipfooter=1, engine='python') I am the skipping the fi

Solution 1:

One possible solution is write DataFrame with NaNs first and then append original DataFrame:

df1 = pd.DataFrame({'a':[np.nan] * 2})
df1.to_csv('output.csv', index=False, header=None)
df.to_csv('output.csv', sep=';', encoding = "ISO-8859-1", mode='a')

Or same original header to df1 and this write first, only necessary no value | in header data:

df1 = pd.read_csv('input.csv', sep='|', encoding = "ISO-8859-1", nrows=2, names=['tmp'])

df1.to_csv('output.csv', index=False, header=None)
df.to_csv('output.csv', sep=';', encoding = "ISO-8859-1", mode='a')

Solution 2:

You want to copy the header from your original file and write to your new file. Then you append your dataframe by setting mode to 'a'

withopen("my_csv.csv") as f:
    header =''for line inrange(0,header_length_in_lines):
        header +=f.readline()

withopen('my_new_csv.csv','w+') as f:
    f.write(header)
df.to_csv('my_new_csv.csv', mode='a', index=False) 

Post a Comment for "Skip First Rows When Writing Csv (pandas.dataframe.to_csv)"