pandas DataFrame.rename unexpected keyword argument "axis" when using mapper

You're probably using python2 with an old version of pandas. The axis parameter isn't implemented yet for you. You have 3 choices. Either remove the axis parameter and explicitly name columns, as shown below, or pass a map to rename(...), or else update your version of python and pandas.

import pandas as pd  
import numpy as np  
import sys 
print(sys.version) 
print(pd.__version__)

#create a dataframe with two columns named Foo and BAR 
df = pd.DataFrame({" Foo": [1, 2, 3], "BAR ": [4, 5, 6]}) 
print(df)

#rename the columns in the dataframe to strip whitespace and be all lowercase: 
df = df.rename(columns={c:c.strip().lower() for c in df.columns}) 
print(df)

#change the column named foo to moo, and change the column named bar to baz 
df = df.rename(columns={"foo": "moo", "bar": "baz"}) 
print(df) 

Which prints:

2.7.16 [GCC 4.9.3]
0.16.2
    Foo  BAR 
0     1     4
1     2     5
2     3     6

   foo  bar
0    1    4
1    2    5
2    3    6

   moo  baz
0    1    4
1    2    5
2    3    6

Am I looking at an old version of the docs?

No, quite the opposite, in fact. You're looking at the latest version (0.21 as of now). I'm pretty sure you have an older version of pandas.

In the older version, Some of the functions used axis to specify index/columns, whereas other functions used index=... or columns=.... To alleviate this, the devs have made an overhaul of many of the APIs to make them more consistent with each other. rename is one of them.

The code you have works just fine on the latest release, but not anything older, because mapper and axis were introduced in 0.21.

For reference, on older versions, the following alternatives all work -

df.columns = df.columns.str.lower()

And,

df = df.rename(columns=dict(zip(df.columns, df.columns.str.lower())))

Tags:

Python

Pandas