Python数据框-计算指定范围内的出现次数(不是轴!) [英] Python dataframe - count occurrences in a specified range (not axis!)

查看:367
本文介绍了Python数据框-计算指定范围内的出现次数(不是轴!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框(称为df),其中有一个带有时间戳的时间序列(第一列)和几个整数数据列。

I have a dataframe (called df), where there is a time series with a time stamp (first column) and several integer data columns.

TimeStamp国家1国家2

TimeStamp Country 1 Country 2

12:00:00 10.05 21.60

12:00:00 10.05 21.60

11:59:00 11.12 22.33

11:59:00 11.12 22.33

11:58:00 12.18 21.70

11:58:00 12.18 21.70

11:57:00 11.70 21.60

11:57:00 11.70 21.60

11:56:00 11.65 22.33

11:56:00 11.65 22.33

11:55:00 11.70 21.60

11:55:00 11.70 21.60

11:54:00 11.50 22.33

11:54:00 11.50 22.33

11:53:00 11.80 21.80

11:53:00 11.80 21.80

... ... ...

... ... ...

问题:我想计算发生次数在特定范围(不是整个轴!)中的最大值。

Problem: I'd like to count the number of occurrences of a the maximum in a specific range (not the whole axis!).

例如在国家/地区2列中,我想计算1-8行中出现最大值的次数。所以首先我找到最大值:df.iloc [0:7,1] .max()-> 22.33

E.g. In column Country 2, I'd like to count the number of occurrences of the max value in rows 1-8. So first I find the max value: df.iloc[0:7,1].max() -> 22.33

现在我要计算它们,

我正在寻找类似count(范围,目标值)之类的东西

I'm looking for something like count(range, target value)

- > df.count(df.iloc [0:7,1)],df.iloc [0:7,1] .max())

-> df.count(df.iloc[0:7,1)], df.iloc[0:7,1].max())

输出应是一个整数。在这里,最大值(22.33)在定义的范围内出现3次,所以我希望3。

The output should be an integer. Here the max value (which is 22.33) occurs 3 times in the defined range, so I'd expect 3.

感谢您的帮助

推荐答案

按最大值比较过滤后的Series的每个值,并按 True s个值> sum :

Compare each value of filtered Series by maximum and count Trues values by sum:

s = df.iloc[0:7,1]

count = s.eq(s.max()).sum()
#alternative
count = (s == s.max()).sum()

print (count)
3

编辑:使用 Series.between

Use Series.between:

s = df.iloc[0:7,1]

thr = 0.01
#print (s.max() - thr)
#print (s.max() + thr)

count = s.between(s.max() - thr, s.max() + thr).sum()
print (count)
3

这篇关于Python数据框-计算指定范围内的出现次数(不是轴!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆