gpt4 book ai didi

python - 确定 ‘data’ 的平均值,其中 CONTINUOUS cond=True 的最高数量

转载 作者:太空狗 更新时间:2023-10-30 02:41:13 24 4
gpt4 key购买 nike

我有一个带有“data”和“cond”(-ition) 列的 pandas Dataframe。我需要“cond”中具有最多 CONTINUOUS True 对象的行的平均值(数据列的)。

    Example DataFrame:

cond data
0 True 0.20
1 False 0.30
2 True 0.90
3 True 1.20
4 True 2.30
5 False 0.75
6 True 0.80

Result = 1.466, which is the mean value of row-indexes 2:4 with 3 True

我无法使用 groupby 或 pivot 方法找到“矢量化”解决方案。所以我写了一个循环行的函数。不幸的是,对于 100 万行,这大约需要一个小时,这太长了。不幸的是,@jit 装饰并没有显着减少持续时间。

我要分析的数据来自一年多的监控项目,我每 3 小时就有一个包含一百万行的 DataFrame。因此,大约有 3000 个这样的文件。

有效的解决方案非常重要。我也非常感谢 numpy 中的解决方案。

最佳答案

使用来自 Calculating the number of specific consecutive equal values in a vectorized way in pandas 的方法:

df['data'].groupby((df['cond'] != df['cond'].shift()).cumsum()).agg(['count', 'mean'])[lambda x: x['count']==x['count'].max()]
Out:
count mean
cond
3 3 1.466667

通过可调用索引需要0.18.0,对于更早的版本,你可以这样做:

res = df['data'].groupby((df['cond'] != df['cond'].shift()).cumsum()).agg(['count', 'mean'])

res[res['count'] == res['count'].max()]
Out:
count mean
cond
3 3 1.466667

工作原理:

第一部分,df['cond'] != df['cond'].shift() 返回一个 bool 数组:

df['cond'] != df['cond'].shift()
Out:
0 True
1 True
2 True
3 False
4 False
5 True
6 True
Name: cond, dtype: bool

因此只要行与上面相同,该值就为 False。这意味着如果您采用累计和,这些行(连续行)将具有相同的数字:

(df['cond'] != df['cond'].shift()).cumsum()
Out:
0 1
1 2
2 3
3 3
4 3
5 4
6 5
Name: cond, dtype: int32

由于 groupby 接受任何要分组的系列(不需要传递列,您可以传递任意列表),这可用于对结果进行分组。 .agg(['count', 'mean'] 部分仅给出每个组的各自计数和均值,最后选择计数最高的一个。

请注意,这也会将连续的 False 组合在一起。如果只想考虑连续的 True,可以将分组 Series 更改为:

((df['cond'] != df['cond'].shift()) | (df['cond'] != True)).cumsum()

因为当条件为真时我们想要假,条件变为“不等于下面的行不为真”。所以原来的行会变成:

df['data'].groupby(((df['cond'] != df['cond'].shift()) | (df['cond'] != True)).cumsum()).agg(['count', 'mean'])[lambda x: x['count']==x['count'].max()]

关于python - 确定 ‘data’ 的平均值,其中 CONTINUOUS cond=True 的最高数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075164/

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