這里記錄一個思路:
假設有一個dataframe,索引為時間(格式為年-月—日 時:分:秒
),要求每一年中符合特定要求(如氣溫最熱)的時間。
就是需要先按照年份進行分組,再求組中的對應值。
思路一
將時間索引中的年份單獨提出來當成一列,再使用groupby()
和apply()
方法來求對應值。
這是實現案例
思路二
還是按照分組的思路,使用resample()
對時間頻率進行分組,再遍歷和篩選(如max()
方法)各個組中的要素。
這個思路是在刷pandas手冊時想起來的。
下面貼出來其中的手冊示例代碼。
In [325]: small = pd.Series(
.....: range(6),
.....: index=pd.to_datetime(
.....: [
.....: "2017-01-01T00:00:00",
.....: "2017-01-01T00:30:00",
.....: "2017-01-01T00:31:00",
.....: "2017-01-01T01:00:00",
.....: "2017-01-01T03:00:00",
.....: "2017-01-01T03:05:00",
.....: ]
.....: ),
.....: )
.....:
In [326]: resampled = small.resample("H")
In [327]: for name, group in resampled:
.....: print("Group: ", name)
.....: print("-" * 27)
.....: print(group, end="\n\n")
.....:
Group: 2017-01-01 00:00:00
---------------------------
2017-01-01 00:00:00 0
2017-01-01 00:30:00 1
2017-01-01 00:31:00 2
dtype: int64
Group: 2017-01-01 01:00:00
---------------------------
2017-01-01 01:00:00 3
dtype: int64
Group: 2017-01-01 02:00:00
---------------------------
Series([], dtype: int64)
Group: 2017-01-01 03:00:00
---------------------------
2017-01-01 03:00:00 4
2017-01-01 03:05:00 5
dtype: int64