gpt4 book ai didi

python-3.x - 高于阈值的数据帧列计数

转载 作者:行者123 更新时间:2023-12-02 22:43:01 25 4
gpt4 key购买 nike

我有一个数据框,我想在其中查找高于阈值的所有 ID 的计数。例如

  index  DEVICE_ID DIFF
0 12 3
1 12 4
2 12 5
3 12 3
4 13 2
5 13 4
6 13 1
7 14 3
8 14 6

如果“Diff”大于或等于 4,请给出从该索引开始的每个唯一 ID 的 ID 计数,因此上述数据帧将导致:

  {12:3, 13:2, 14:1} - For ID 12, the diff column is 4 on index 1 so we count the amount of 12's from and including index 1 till 3

很抱歉这个问题措辞不好。

最佳答案

Series.ge 比较列(>=) 首先,然后按 df['DEVICE_ID'] 分组并使用 cumsum ,比较Series.gt并聚合 sum 计数 True 值:

s = df['DIFF'].ge(4).groupby(df['DEVICE_ID']).cumsum().gt(0).astype(int)

out = s.groupby(df['DEVICE_ID']).sum().to_dict()
print (out)
{12: 3, 13: 2, 14: 1}

详细信息:

print (df['DIFF'].ge(4).groupby(df['DEVICE_ID']).cumsum())
index
0 0.0
1 1.0
2 2.0
3 2.0
4 0.0
5 1.0
6 1.0
7 0.0
8 1.0
Name: DIFF, dtype: float64

另一种解决方案,其索引为 DEVICE_ID,然后按 level=0 的索引进行 gro,最后仅使用每个索引的 sum (级别=0):

out = (df.set_index(['DEVICE_ID'])['DIFF']
.ge(4)
.groupby(level=0)
.cumsum()
.gt(0)
.astype(int)
.sum(level=0)
.to_dict())

关于python-3.x - 高于阈值的数据帧列计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com