I have this dataframe:
content
id
17 B
17 A
6 A
15 A
...
我想要统计索引为17的行有多少条(在这个例子中是2)。 有没有一种方法可以做到这一点?
sum(df.index == 17)
df.index == 17
返回一个数组,其中boolean
值为True
表示索引值匹配,否则为False
。同时,在使用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
testd_df.index.value_counts()
。 - sanzoghenzodf.groupby(level=0).count()
reset_index()
df.reset_index().groupby('id').count()
df[df.index==17]
- BENY
df.index == 17
的时候,你得到了[1 1 1 ..., 0 0 0]
吗?这对于提供的示例样本不起作用吗? - niraj