# 如何根据列中的条件进行计算？

``````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
``````

``````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)))
}

``````

``````# 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]
``````

``````
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()
``````

0 条评论