我有這樣的數據幀:的Python /大熊貓 - 計算行數與某些指數
content
id
17 B
17 A
6 A
15 A
...
我要計算有多少行具有指數17(在這種情況下,這將是2)。 有沒有辦法做到這一點?
我有這樣的數據幀:的Python /大熊貓 - 計算行數與某些指數
content
id
17 B
17 A
6 A
15 A
...
我要計算有多少行具有指數17(在這種情況下,這將是2)。 有沒有辦法做到這一點?
你可以試試:
sum(df.index == 17)
df.index == 17
當指數值否則匹配False
返回與boolean
的陣列True
。而 使用sum
函數True
相當於1
。
可以GROUPBY水平
df.groupby(level=0).count()
或者reset_index()
df.reset_index().groupby('id').count()
但我該如何訪問17? df.groupby(級別= 0).Count之間()。LOC [17]? – abutremutante
@abutremutante'df [df.index == 17]' – Wen
我得到的結果像[1 1 1 ...,0 0 0]。我只是想知道在使用'df.index == 17'時你有多少次17出現在索引 – abutremutante
@abutremutante中,你有'[1 1 1,...,0 0 0]'?它是否適用於提供的示例示例? – 0p3n5ourcE
你是對的,它的確如此。因爲我的DF很大,我試圖在這裏簡化,但顯然不是最好的方法。無論如何,我解決了一個不是pythonic的方式:a = 0,因爲我在df.index:if i == 17:a + = 1 – abutremutante