Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas overwrite column names by position

I'm reading in a csv, and I'd like to overwrite the first two column names.

  • I can't use df.rename(columns={0:'name 1', 1:'name 2'}) because the columns aren't called 0 and 1. They have names, I just want to throw them out.

  • It seems like

    df.columns.values[0] = 'name 1'
    df.columns.values[1] = 'name 2'
    

    has serious issues because afterwards, df['name 1'] gives me a KeyError.

  • What would be ideal would be pd.read_csv(file, names=['name 1', 'name 2', ...]. Curiously, this renames col 3 "Ellipsis" and doesn't have the desired effect.

Any ideas for how to do this sensibly in pandas?

like image 892
Alex Lenail Avatar asked Dec 07 '25 15:12

Alex Lenail


1 Answers

Try this:

df.columns = ['name 1', 'name 2'] + df.columns[2:].tolist()
like image 191
MaxU - stop WAR against UA Avatar answered Dec 09 '25 06:12

MaxU - stop WAR against UA