[英]Python / Pandas - Count number of rows with certain index
我有這個數據框:
content
id
17 B
17 A
6 A
15 A
...
我想計算索引為17的行數(在這種情況下為2)。 有沒有辦法做到這一點?
您可以按級別分組
df.groupby(level=0).count()
或reset_index()
df.reset_index().groupby('id').count()
你可以試試:
sum(df.index == 17)
當索引值匹配else False
時, df.index == 17
返回一個boolean
值為True
的數組。 並且在使用sum
函數True
等於1
。
Input: # Your DataFrame
test_dict = {'id': ['17', '17', '6', '15'], 'content': ['B', 'A', 'A', 'A']}
testd_df = pd.DataFrame.from_dict(test_dict) # create DataFrame from dict
testd_df.set_index('id', inplace=True) # set 'id' as index in inplace way
testd_df
Output:
|content
--------------
id |
-------------
17 | B
17 | A
6 | A
15 | A
pandas.Index.value_counts
根據該文檔, pandas.Index.value_counts
將返回包含唯一值計數的對象,並返回pd.Series
。
所以現在,我可以使用pandas.Series.loc
選擇想要的特定索引 (不要與.iloc
混淆)
# Solution
Input: index_count = pd.Index(testd_df.index).value_counts() # count value of unique value
index_count
Output: 17 2
15 1
6 1
dtype: int64
---------------------------------
Input: index_count.loc['17'] # select the information you care about
Output: 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.