簡體   English   中英

Python / Pandas-計算具有特定索引的行數

[英]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

解決方案:使用api 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM