【发布时间】:2014-10-14 19:30:32
【问题描述】:
我有一个带有结构的 sample_data.txt。
Precision= Waterdrops
2009-11-17 14:00:00,4.9,
2009-11-17 14:30:00,6.1,
2009-11-17 15:00:00,5.3,
2009-11-17 15:30:00,3.3,
2009-11-17 16:00:00,4.9,
我需要将我的数据与大于零的值分开,并识别时间垃圾大于 2 小时的变化(事件)。到目前为止,我已经写了:
file_path = 'sample_data.txt'
df = pd.read_csv(file_path, skiprows = [num for (num,line) in enumerate(open(file_path),2) if 'Precision=' in line][0],
parse_dates = True,index_col = 0,header= None, sep =',',
names = ['meteo', 'empty'])
df['date'] = df.index
df = df.drop(['empty'], axis=1)
df = df[df.meteo>20]
df['diff'] = df.date-df.date.shift(1)
df['sections'] = (diff > np.timedelta64(2, "h")).astype(int).cumsum()
从上面的代码我得到:
meteo date diff sections
2009-12-15 12:00:00 23.8 2009-12-15 12:00:00 NaT 0
2009-12-15 13:00:00 23.0 2009-12-15 13:00:00 01:00:00 0
如果我使用:
df.date.iloc[[0, -1]].reset_index(drop=True)
我明白了:
0 2009-12-15 12:00:00
1 2012-12-05 16:00:00
Name: date, dtype: datetime64[ns]
哪个是我的 example_data.txt 的开始日期和结束日期。
如何为每个 df['section'] 类别获取 .iloc[[0, -1]].reset_index(drop=True) ?
我尝试使用 .apply:
def f(s):
return s.iloc[[0, -1]].reset_index(drop=True)
df.groupby(df['sections']).apply(f)
我得到:IndexError:位置索引器超出范围
【问题讨论】: