Python/Pandas-使用特定索引计算行数
我有这个数据框:Python/Pandas-使用特定索引计算行数,python,pandas,Python,Pandas,我有这个数据框: content id 17 B 17 A 6 A 15 A ... 我想计算有多少行具有索引17(在本例中为2)。 有办法吗?您可以按级别分组 df.groupby(level=0).count() 或reset\u index() 您可以尝试: sum(df.index == 17) df.index==17当索引值与elseFalse匹配时,返回带有boolean和True的
content
id
17 B
17 A
6 A
15 A
...
我想计算有多少行具有索引17(在本例中为2)。
有办法吗?您可以按级别分组
df.groupby(level=0).count()
或reset\u index()
您可以尝试:
sum(df.index == 17)
df.index==17
当索引值与elseFalse
匹配时,返回带有boolean
和True
的数组。而
使用sum
函数True
相当于1
问题:如何计算索引标签的数量?
解决方案:使用api
根据文档,pandas.Index.value\u counts
将返回包含唯一值计数的对象,并返回一个pd.Series
现在,我可以通过使用(不要与.iloc
混淆)选择我想要的特定索引
但我如何进入17号公路?df.groupby(level=0.count().loc[17]?@abutemutate
df[df.index==17]
Hi,我的案例还有一列是date。如果日期>='2019-01-01'(例如)我得到的结果类似于[1,1,0],我如何计算行数。我只想知道17在电视上出现了多少次index@abutremutante你的意思是当使用df.index==17
时,你得到了[1,1,0,0]
?它对提供的示例不起作用吗?你是对的,它起作用了。由于我的df很大,我试图在这里简化,但显然不是最好的方法。无论如何,我用一种不太符合Python的方式解决了:a=0,对于df.index中的I:如果I==17:a+=1,则无需创建新的索引,只需使用testd\u df.index.value\u counts()
sum(df.index == 17)
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
# 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