Diganta Bharali
Diganta Bharali

Reputation: 71

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

Upvotes: 2

Views: 2351

Answers (2)

alecxe
alecxe

Reputation: 473813

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

Upvotes: 2

chrymxbrwn
chrymxbrwn

Reputation: 98

Theres a better way to do this using df.rename; but this will work:

df['Id'] = df['idSite'] 
df = df.drop('idSite', axis=1)

you should be able to find a solution in another thread

Upvotes: 0

Related Questions