我想将所有值设置为某个值(例如999)在某个时间段(例如1小时)内超过某个阈值(例如7)出现的某个值。我曾经使用过一些怪异的非矢量化方法,但有些运气,但是必须有一种更好的,泛泛的方法。
一个例子是:
设置随机数据帧:
return new Promise(resolve => {
let initialCall = true;
API.addEventListener(newState => {
cacheStorage.state = newState;
if (initialCall) {
resolve(newState);
initialCall = false;
}
}, /* repeating */ true);
});
随机输出:
hr_rng = pd.date_range(start='7/1/2014 00:00:00', end='7/1/2014 10:00:00', freq='H')
df = pd.DataFrame(hr_rng, columns=['date_time'])
df.set_index(pd.DatetimeIndex(df['date_time']),inplace=True)
df['val0']=np.random.randint(1, 10, df.shape[0])
我想回来的是这个
date_time val0
date_time
2014-07-01 00:00:00 2014-07-01 00:00:00 4
2014-07-01 01:00:00 2014-07-01 01:00:00 8
2014-07-01 02:00:00 2014-07-01 02:00:00 4
2014-07-01 03:00:00 2014-07-01 03:00:00 7
2014-07-01 04:00:00 2014-07-01 04:00:00 2
2014-07-01 05:00:00 2014-07-01 05:00:00 4
2014-07-01 06:00:00 2014-07-01 06:00:00 4
2014-07-01 07:00:00 2014-07-01 07:00:00 9
2014-07-01 08:00:00 2014-07-01 08:00:00 1
2014-07-01 09:00:00 2014-07-01 09:00:00 9
2014-07-01 10:00:00 2014-07-01 10:00:00 5
另一个随机示例:
date_time val0
date_time
2014-07-01 00:00:00 2014-07-01 00:00:00 999
2014-07-01 01:00:00 2014-07-01 01:00:00 999
2014-07-01 02:00:00 2014-07-01 02:00:00 999
2014-07-01 03:00:00 2014-07-01 03:00:00 7
2014-07-01 04:00:00 2014-07-01 04:00:00 2
2014-07-01 05:00:00 2014-07-01 05:00:00 4
2014-07-01 06:00:00 2014-07-01 06:00:00 999
2014-07-01 07:00:00 2014-07-01 07:00:00 999
2014-07-01 08:00:00 2014-07-01 08:00:00 999
2014-07-01 09:00:00 2014-07-01 09:00:00 999
2014-07-01 10:00:00 2014-07-01 10:00:00 999
应该变成这样:
date_time val0
date_time
2014-07-01 00:00:00 2014-07-01 00:00:00 5
2014-07-01 01:00:00 2014-07-01 01:00:00 6
2014-07-01 02:00:00 2014-07-01 02:00:00 3
2014-07-01 03:00:00 2014-07-01 03:00:00 2
2014-07-01 04:00:00 2014-07-01 04:00:00 9
2014-07-01 05:00:00 2014-07-01 05:00:00 7
2014-07-01 06:00:00 2014-07-01 06:00:00 6
2014-07-01 07:00:00 2014-07-01 07:00:00 8
2014-07-01 08:00:00 2014-07-01 08:00:00 6
2014-07-01 09:00:00 2014-07-01 09:00:00 7
2014-07-01 10:00:00 2014-07-01 10:00:00 3
答案 0 :(得分:0)
IIUC是一种方法:
import pandas as pd
import numpy as np
np.random.seed(42)
hr_rng = pd.date_range(start='7/1/2014 00:00:00',
end='7/1/2014 10:00:00',
freq='H')
df = pd.DataFrame(hr_rng, columns=['date_time'])
df.set_index(pd.DatetimeIndex(df['date_time']),inplace=True)
df['val0']=np.random.randint(1, 10, df.shape[0])
现在,更新等于或大于阈值的行。
threshold = 7
# initialize
df['test'] = df['val0']
mask = df['val0'] >= threshold
df.loc[mask, 'test'] = 999
print(df.head())
date_time val0 test
date_time
2014-07-01 00:00:00 2014-07-01 00:00:00 7 999
2014-07-01 01:00:00 2014-07-01 01:00:00 4 4
2014-07-01 02:00:00 2014-07-01 02:00:00 8 999
2014-07-01 03:00:00 2014-07-01 03:00:00 5 5
2014-07-01 04:00:00 2014-07-01 04:00:00 7 999
您是否有关于查找和更新所选值的问题?还是将观察结果放入一小时的时段中?