2016-11-23 62 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