gpt4 book ai didi

python - 如何根据列中的条件进行计算?

转载 作者:行者123 更新时间:2023-11-28 18:56:42 24 4
gpt4 key购买 nike

当有一组连续跟随时,我想做一个计算。

我有一个关于压缩机工作原理的数据库。每隔 5 分钟,我会获取压缩机状态(如果它是开/关)以及此刻消耗的电量。 On_Off 列在压缩机工作(ON)时有一个1,在它关闭时有一个0

Compresor = pd.Series([0,0,1,1,1,0,0,1,1,1,0,0,0,0,1,1,1,0], index = pd.date_range('1/1/2012', periods=18, freq='5 min'))
df = pd.DataFrame(Compresor)
df.index.rename("Date", inplace=True)
df.set_axis(["ON_OFF"], axis=1, inplace=True)
df.loc[(df.ON_OFF == 1), 'Electricity'] = np.random.randint(4, 20, df.sum())
df.loc[(df.ON_OFF < 1), 'Electricity'] = 0
df


ON_OFF Electricity
Date
2012-01-01 00:00:00 0 0.0
2012-01-01 00:05:00 0 0.0
2012-01-01 00:10:00 1 4.0
2012-01-01 00:15:00 1 10.0
2012-01-01 00:20:00 1 9.0
2012-01-01 00:25:00 0 0.0
2012-01-01 00:30:00 0 0.0
2012-01-01 00:35:00 1 17.0
2012-01-01 00:40:00 1 10.0
2012-01-01 00:45:00 1 5.0
2012-01-01 00:50:00 0 0.0
2012-01-01 00:55:00 0 0.0
2012-01-01 01:00:00 0 0.0
2012-01-01 01:05:00 0 0.0
2012-01-01 01:10:00 1 14.0
2012-01-01 01:15:00 1 5.0
2012-01-01 01:20:00 1 19.0
2012-01-01 01:25:00 0 0.0

我想做的是只在有一组的时候加上耗电量,再做一个Data.Frame。例如:

enter image description here

在这个例子中,压缩机第一次打开是在 00:20 -00:30 之间。期间消耗了25(10+10+5)。第二次它在 (00:50-01:15) 持续更长时间,并在此间隔 50 (10+10+10+10+10+5+5) 内消耗。第三次它消耗了 20 (10 + 10)。

我想自动执行此操作我是 pandas 的新手,我想不出办法。

最佳答案

假设您有以下数据:

from operator import itemgetter

import numpy as np
import numpy.random as rnd
import pandas as pd
from funcy import concat, repeat
from toolz import partitionby

base_data = {
'time': list(range(20)),
'state': list(concat(repeat(0, 3), repeat(1, 4), repeat(0, 5), repeat(1, 6), repeat(0, 2))),
'value': list(concat(repeat(0, 3), rnd.randint(5, 20, 4), repeat(0, 5), rnd.randint(5, 20, 6), repeat(0, 2)))
}

嗯,有两种方法:

第一个是功能性的并且独立于 pandas:您只需按字段对数据进行分区,即该方法按顺序处理数据并每隔一段时间生成一个新分区字段值变化的时间。然后,您可以根据需要简单地汇总每个分区。

# transform into sample data
sample_data = [dict(zip(base_data.keys(), x)) for x in zip(*base_data.values())]
# and compute statistics the functional way
[sum(x['value'] for x in part if x['state'] == 1)
for part in partitionby(itemgetter('state'), sample_data)
if part[0]['state'] == 1]

还有 pandas 方式,类似于@ivallesp 提到的方式:您可以通过移动状态列来计算状态的变化。那你summarize your data frame by the group


pd_data = pd.DataFrame(base_data)
pd_data['shifted_state'] = pd_data['state'].shift(fill_value = pd_data['state'][0])
pd_data['cum_state'] = np.cumsum(pd_data['state'] != pd_data['shifted_state'])
pd_data[pd_data['state'] == 1].groupby('cum_state').sum()

根据您和您的同龄人最擅长阅读的内容,您可以选择自己的方式。此外,功能方式可能不容易阅读,也可以用可读的循环语句重写。

关于python - 如何根据列中的条件进行计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397937/

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