Diganta Bharali Diganta Bharali - 3 months ago 5x
Python Question

Renaming columns in csv by column index

I have a csv file:

visitIp userId idSite a 35 a 35 a 35 a 35 a 35 a 35

I want to rename the column in the third index that is 'idSite' to just Id. The reason I want to do it by index is that there might be other csvs that have different column names in the 3rd column. So i need to rename by index as not by name. This is what i tried. But it does not seem to be working:

import pandas as pd
df = pd.read_csv('Book1.csv',dtype='unicode')
df1 = df.rename(columns = {'df.ix[:,2:3]':'id'})
print df1


You can rename the column setting the .columns.values[2] value directly:

import pandas as pd

df = pd.read_csv('Book1.csv', dtype='unicode', delim_whitespace=True)
df.columns.values[2] = "id"


          visitIp userId  id
0      a  35
1      a  35
2      a  35
3      a  35
4      a  35
5      a  35