Series.count level is only valid with a MultiIndex
Package:
pandas
30911

Exception Class:
ValueError
Raise code
"Using the level keyword in DataFrame and Series aggregations is "
"deprecated and will be removed in a future version. Use groupby "
"instead. ser.count(level=1) should use ser.groupby(level=1).count().",
FutureWarning,
stacklevel=2,
)
if not isinstance(self.index, MultiIndex):
raise ValueError("Series.count level is only valid with a MultiIndex")
index = self.index
assert isinstance(index, MultiIndex) # for mypy
if isinstance(level, str):
level = index._get_level_number(level)
Links to the raise (1)
https://github.com/pandas-dev/pandas/blob/b3e335254f46a526ee3ce9bb757eac4011d9d1fe/pandas/core/series.py#L1907Ways to fix
Error code:
import pandas as pd
import numpy as np
index = [1,2,3,4,6,7,8]
s = pd.Series(np.random.randn(8),index)
s.count(level=1)
Pandas.Series.count
returns number of non-NA/null
observations in the Series.
If the index of Series is not instance of MultiIndex
, it will not possible to count the number of non-Na/null observations.
Fix code:
import pandas as pd
import numpy as np
iterables = [["bar", "baz", "foo", "qux"], ["one", "two"]]
index = pd.MultiIndex.from_product(iterables,names=["first", "second"])
# We created MultiIndex and initial it as a index of Series
s = pd.Series(np.random.randn(8),index)
s.count(level=1)
Add a possible fix
Please authorize to post fix