Reputation: 73
I have a csv dataframe which I want to save with an extra header, apart from the columns. pandas must read my file without the header:
pd.read_csv('file.csv', header=2)
After editing the csv file, I would like to save it with a new header, e.g. it is supposed to look like this:
no rows = 4
no cols = 3
index, col1, col2, col3
0, A, B, C
1, D, E, F
2, G, H, I
3, J, L, M
But the the header argument in the to_csv
function seems to be dependent on the columns as aliases according to the docs (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html)
The header would count each row as one cell, therefore a 1col x 2row df. I thought about appending the two, but due to unequal columns it wouldn't work. Is there an easy way to add an independent header to a csv-file?
I couldn't find a post with this problem, any help will be appreciated!
Upvotes: 5
Views: 2828
Reputation: 34046
So, when you want to read the file without
header in to pandas. Do:
df = pd.read_csv('file.csv', header=None)
Now, after doing all sort of processing in df
, you can assign column_names
as per your choice like:
col_list = ['col1','col2','col3']
df.columns = col_list
Now, write this df
back to csv using to_csv
:
df.to_csv('/new_file.csv', index=None, header=None)
You can paste your 2-line header to the top of this file by writing it like this:
with open('/new_file.csv', 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write('my_2-line_header' + '\n' + content)
Hope this helps.
Upvotes: 4