Renaming columns

import pandas as pd

Set column names on reading a data file.

column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'target']
iris = pd.read_csv('../data/iris.csv', names=column_names)

iris.head()
sepal_length sepal_width petal_length petal_width target
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa

Set column names for an existing dataframe.

iris = pd.read_csv('../data/iris.csv')

column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'target']
iris.columns = column_names

iris.head()
sepal_length sepal_width petal_length petal_width target
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
2 4.6 3.1 1.5 0.2 Iris-setosa
3 5.0 3.6 1.4 0.2 Iris-setosa
4 5.4 3.9 1.7 0.4 Iris-setosa

Rename individual columns.

iris.rename(columns={'target': 'species'}, inplace=True)

iris.head()
sepal_length sepal_width petal_length petal_width species
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
2 4.6 3.1 1.5 0.2 Iris-setosa
3 5.0 3.6 1.4 0.2 Iris-setosa
4 5.4 3.9 1.7 0.4 Iris-setosa

Rename with a function.

iris.rename(columns=lambda x: 'col_' + x, inplace=True)

iris.head()
col_sepal_length col_sepal_width col_petal_length col_petal_width col_species
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
2 4.6 3.1 1.5 0.2 Iris-setosa
3 5.0 3.6 1.4 0.2 Iris-setosa
4 5.4 3.9 1.7 0.4 Iris-setosa

Get column names.

print(iris.columns)
Index(['col_sepal_length', 'col_sepal_width', 'col_petal_length',
       'col_petal_width', 'col_species'],
      dtype='object')

If you spot any errors please let me know on twitter.