这里记录一个思路:
假设有一个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