Last updated: Apr 12, 2024
Reading time·3 min
axis
parameter incorrectlyThe Pandas error "ValueError: No axis named X for object type DataFrame" most
commonly occurs when you pass multiple column names to DataFrame.groupby()
but
forget to wrap them in a list []
.
To solve the error, wrap the column names in a list by surrounding them with
square brackets when calling groupby()
.
Here is an example of how the error occurs.
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 25, 40, 45, 45, 65] }) # ⛔️ ValueError: No axis named Max Speed for object type DataFrame print(df.groupby('Animal', 'Max Speed'))
We called the DataFrame.groupby method with multiple column names but forgot to wrap them in a list.
You can solve the error by wrapping the column names in a list when calling
groupby()
.
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 25, 40, 45, 45, 65] }) # <pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f40c1f8d2a0> print(df.groupby(['Animal', 'Max Speed'])) print('-' * 50) # Animal Max Speed # Cat 25 2 # 40 1 # Dog 45 2 # 65 1 # Name: Animal, dtype: int64 print(df.groupby(['Animal', 'Max Speed'])['Animal'].count())
The DataFrame.groupby()
method groups the DataFrame
on one or more columns.
The first argument the method takes is used to determine the groups for the
groupby
.
The argument can be a label or a list of labels (for multiple columns).
axis
parameter incorrectlyYou might also get the error if you set the axis
parameter incorrectly.
import pandas as pd import numpy as np df = pd.DataFrame( {'A': np.array([1, 2, 3, 4, 5, 6])} ) # ⛔️ ValueError: No axis named -1 for object type DataFrame print(np.mean(df, axis=-1))
We called the numpy.mean() method with a
DataFrame
and set the axis
parameter to -1
which caused the error.
You can try to omit the axis
parameter.
import pandas as pd import numpy as np df = pd.DataFrame( {'A': np.array([1, 2, 3, 4, 5, 6])} ) print(np.mean(df)) # 👉️ 3.5
The axis
parameter can also be set if you pass a NumPy array to
numpy.mean()
, and not a DataFrame
.
import numpy as np arr = np.array([[1, 2], [3, 4], [5, 6]]) print(np.mean(arr, axis=-1)) # 👉️ [1.5 3.5 5.5] print(np.mean(arr, axis=1)) # 👉️ [1.5 3.5 5.5]
If you need to calculate the mean of the values over a specific axis in a
DataFrame
, use the
DataFrame.mean()
method.
import pandas as pd import numpy as np df = pd.DataFrame( {'A': np.array([1, 2, 3, 4, 5, 6])} ) # A 3.5 # dtype: float64 print(df.mean())
You can learn more about the related topics by checking out the following tutorials: