在保持价值关联的同时对熊猫进行重新取样

csg*_*136 5 python datetime pandas

从这样的事情开始:

from pandas import DataFrame
time = np.array(('2015-08-01T00:00:00','2015-08-01T12:00:00'),dtype='datetime64[ns]')
heat_index = np.array([101,103])
air_temperature = np.array([96,95])

df = DataFrame({'heat_index':heat_index,'air_temperature':air_temperature},index=time)
Run Code Online (Sandbox Code Playgroud)

产生这个df:

                     air_temperature    heat_index
2015-08-01 07:00:00  96                 101
2015-08-01 19:00:00  95                 103
Run Code Online (Sandbox Code Playgroud)

然后每天重新采样:

df_daily = df.resample('24H',how='max')
Run Code Online (Sandbox Code Playgroud)

为此得到df_daily:

            air_temperature     heat_index
2015-08-01  96                  103
Run Code Online (Sandbox Code Playgroud)

因此,通过how='max'每24小时使用pandas重新采样重新采样,从每列中获取该时间段内的最大值.

但正如你所看到的看着df输出2015-08-01,当天的最大热指数(发生在19:00:00)不相关的空气温度发生在同一时间.也就是说,在空气温度为95°F时引起103°的热指数.这种关联通过重新取样而丢失,我们最终会从一天中的不同时间看到空气温度.

有没有办法只重新采样一列,并将值保留在同一索引的另一列中?所以最终结果如下:

            air_temperature     heat_index
2015-08-01  95                  103
Run Code Online (Sandbox Code Playgroud)

我的第一个猜测就是重新对该heat_index列进行重新采样......

df_daily = df.resample('24H',how={'heat_index':'max'})
Run Code Online (Sandbox Code Playgroud)

要得到...

            air_temperature
2015-08-01  103
Run Code Online (Sandbox Code Playgroud)

...然后尝试从那里做某种DataFrame.loc或DataFrame.ix,但一直没有成功.关于如何在重新采样后找到相关值的任何想法(例如,找到与air_temperature后来发现的最大值同时发生的值heat_index)?

chr*_*isb 2

这是一种方法 -.groupby(TimeGrouper())本质上就是正在做的事情resample,然后聚合函数将每个组过滤到最大观察值。

In [60]: (df.groupby(pd.TimeGrouper('24H'))
            .agg(lambda df: df.loc[df['heat_index'].idxmax(), :]))

Out[60]: 
            air_temperature  heat_index
2015-08-01               95         103
Run Code Online (Sandbox Code Playgroud)