I have a text file which I want to read with pandas. Later I want to save that text file in csv format and I also want to add column names while saving csv file.
When my file is saved in csv format, the first row is replaced by the column names. This is my code
df = pd.read_csv('files.txt', delim_whitespace= True, header=0)
d = dict(zip(df.columns[::],
['Column{}'.format(x) for x in range(len(df.columns[::]))]))
Finally, I want to rename the column names and everything is work except my new column names replace the first rows
df = df.rename(columns = d)
df.to_csv('test.csv', index= 0)
I am not sure why my first row is replaced with my column names.
header=0 means "I want the header to be the taken from the 0th row of my file".
You instead want header=None, which means "my file does not have a header at all".
Note, you can shorten your renaming script to
df.columns = 'Column' + df.columns.astype(str)
Which modifies the column headers in-place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With