Skip to main content
 首页 » 编程设计

Python Pandas 计数

2024年10月01日9zhwl

我有一个“句子”数据框,我希望从中搜索关键字。假设我的关键字只是字母“A”。示例数据:

year | sentence | index 
----------------------- 
2015 | AAX      | 0 
2015 | BAX      | 1 
2015 | XXY      | -1 
2016 | AWY      | 0 
2017 | BWY      | -1 

即“索引”列显示每个句子中第一次出现“A”的索引(如果找不到则为-1)。我想将这些行分组到各自的年份,其中一列显示每年记录中“A”出现的百分比。即:

year | index 
------------- 
2015 | 0.667 
2016 | 1.0 
2017 | 0 

我感觉这在某种程度上涉及 agg 或 groupby,但我不清楚如何将它们串在一起。我已经做到了:

df.groupby("index").count()

但这里的问题首先是某种条件 count(),我们首先计算 201X 年包含“A”的行数,然后将其除以 201X 年的行数。

请您参考如下方法:

您可以使用 value_counts或 GroupBy.size与 boolean indexing :

What is the difference between size and count in pandas?

df2 = df['year'].value_counts() 
print (df2) 
2015    3 
2017    1 
2016    1 
Name: year, dtype: int64 
 
df1 = df.loc[df['index'] != -1, 'year'].value_counts() 
print (df1) 
2015    2 
2016    1 
Name: year, dtype: int64 

或者:

df2 = df.groupby('year').size() 
print (df2) 
year 
2015    3 
2016    1 
2017    1 
dtype: int64 
 
df1 = df.loc[df['index'] != -1, ['year']].groupby('year').size() 
print (df1) 
year 
2015    2 
2016    1 
dtype: int64 

最后除以 div :

print (df1.div(df2, fill_value=0)) 
2015    0.666667 
2016    1.000000 
2017    0.000000 
Name: year, dtype: float64