2016-11-23 5 views

ответ

0

Единственное, что я знаю, это сбросить индекс перед выполнением groupby. Ниже я привел простой пример для воспроизводства, он должен быть адаптирован к вашему прецеденту.

Он должен работать, но может быть и лучшее решение. Я взгляну.

# Creating test data 
np.random.seed(0) 
df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), 
        columns=list('ABCD')) 
df = df.set_index(['A', 'B']) 

# Reset the index, 
# group by the first level and count the number of second level 
# nunique can also be used to get the number of unique values 

df.reset_index(level=1).groupby(level=0)['B'].count() 

# A 
# 2 1 
# 3 1 
# 4 1 
# 5 3 
# 7 2 
# 8 2 

Редактировать

Вот я думаю, что лучшее решение, используя большой value_counts метод по индексу.

df.reset_index(level=1).index.value_counts() 

# 5 3 
# 8 2 
# 7 2 
# 4 1 
# 3 1 
# 2 1