Pandas TypeError 'list' object is not callable - rename Pandas columns
The Pandas error 'list' object is not callable
is raised when we try to rename dataframe columns. Usually this means that we try to use list instead of a dict with method: .rename()
.
df.rename(columns=['A', 'B', 'C'])
results into:
TypeError: 'list' object is not callable
while
cols = {'A':'AA', 'B': 'BB', 'C': 'CC'}
df.rename(columns=cols)
works fine.
Here's how to correctly rename columns in pandas and avoid the error:
1. Rename with a dictionary using .rename()
The correct syntax for renaming Pandas columns is:
df = df.rename(columns={'old_name': 'new_name'})
Below you can find full example of renaming columns:
import pandas as pd
df = pd.DataFrame({
"A": [0, 1, 2, 3],
"B": [3, 5, 7, 9],
"C": [1, 2, 3, 4]
})
cols = {'A':'AA', 'B': 'BB', 'C': 'CC'}
df.rename(columns=cols)
2. Replace all headers at once using df.columns = [...]
df.columns = ['AA', 'BB', 'CC']
3. Mistake TypeError: 'Index' object is not callable
Similar miskate TypeError: 'Index' object is not callable
is raised when we try to invoke dataframe attribute as a method:
df.columns('name', 'age', 'country')
This is because df.columns
is attribe, and we're using ()
as if it were a function.
Error:
df.columns('A', 'B', 'C')
Solution:
df.columns = ['A', 'B', 'C']
This typically happens with incorrect use of parentheses ()
instead of square brackets []
.
In this short post we saw the reasons and solutions for 2 typical Pandas errors:
TypeError: 'list' object is not callable
TypeError: 'Index' object is not callable