我有以下Pandas多索引DataFrame,其顶级索引是组ID,第二级索引是when
ISO 8601时间格式(此处显示的没有时间):
value weight
when
5e33c4bb4265514aab106a1a 2011-05-12 1.34 0.79
2011-05-07 1.22 0.83
2011-05-03 2.94 0.25
2011-04-28 1.78 0.89
2011-04-22 1.35 0.92
... ... ...
5e33c514392b77d517961f06 2009-01-31 30.75 0.12
2009-01-24 30.50 0.21
2009-01-23 29.50 0.96
2009-01-10 28.50 0.98
2008-12-08 28.50 0.65
when
当前定义为,index
但这不是必需条件。
when
可能是不唯一的。when
,value
并且weight
将始终具有相等的长度(对于每个组,when
总会有a value
和aweight
使用参数index_time
,如何检索:
value
和weight
从每个相组index_time
之间与所述差(秒)沿index_time
和when
。index_time
可能是过去的时间,因此仅选择when
<=的条目index_time
。根据以上所述,如果index_time
是,2011-05-10
则结果应为:
value weight age
5e33c4bb4265514aab106a1a 1.22 0.83 259200
5e33c514392b77d517961f06 30.75 0.12 72576000
DataFrame
问题中给出的原始文件是df
:
import pandas as pd
df.sort_index(inplace=True)
result = df.loc[pd.IndexSlice[:, :when], :].groupby('id').tail(1)
result['age'] = when - result.index.get_level_values(level=1)