Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading file into pandas DataFrame without column header not working

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.

like image 857
user96564 Avatar asked Mar 10 '26 17:03

user96564


1 Answers

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.

like image 83
cs95 Avatar answered Mar 14 '26 06:03

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!