Diganta Bharali Diganta Bharali - 4 months ago 6
Python Question

Renaming columns in csv by column index

I have a csv file:

visitIp userId idSite
128.227.50.161 a 35
24.222.206.154 a 35
10.12.0.1 a 35
10.12.0.1 a 35
10.12.0.1 a 35
24.222.206.154 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

Answer

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"
print(df)

Prints:

          visitIp userId  id
0  128.227.50.161      a  35
1  24.222.206.154      a  35
2       10.12.0.1      a  35
3       10.12.0.1      a  35
4       10.12.0.1      a  35
5  24.222.206.154      a  35
Comments