繁体   English   中英

Python dataframe - 计算指定范围内的出现次数(不是轴!)

[英]Python dataframe - count occurrences in a specified range (not axis!)

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

时间戳 国家 1 国家 2

12:00:00 10.05 21.60

11:59:00 11.12 22.33

11:58:00 12.18 21.70

11:57:00 11.70 21.60

11:56:00 11.65 22.33

11:55:00 11.70 21.60

11:54:00 11.50 22.33

11:53:00 11.80 21.80

…………

问题:我想计算特定范围(而不是整个轴)中最大值的出现次数。

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

现在我想数一数,怎么做?

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

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

output 应该是 integer。 这里的最大值(即 22.33)在定义的范围内出现了 3 次,所以我期望 3。

谢谢你的帮助

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

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

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

print (count)
3

编辑:使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM