简体   繁体   English

Pandas:在数据帧组之后重新采样时间组名称

[英]Pandas: resample time group names after a dataframe groupby

My dataframe looks like 我的数据框看起来像

Time,                           Id             A               B            C                                                                            
2016-06-15 08:09:26.212962  115516             3           3.238     7.790000   
2016-06-15 08:10:13.863304  115517             3           0.000     8.930000   
2016-06-15 08:11:02.236033  115518             3           0.000     9.090000   
2016-06-15 08:11:52.085754  115519             3           0.000     9.420000  

If I apply a groupby like 如果我申请了一个像

grouped = df.groupby(pd.TimeGrouper("5Min"), as_index=False)

I get group names and groups like: 我得到的组名和组如下:

2016-06-15 08:05:00
    2016-06-15 08:09:26.212962
2016-06-15 08:10:00
    2016-06-15 08:10:13.863304
    2016-06-15 08:11:02.236033
    2016-06-15 08:11:52.085754
2016-06-15 08:25:00
    2016-06-15 08:25:41.827770

So my question is how can I resample the group names formed above and fill non existent groups with None to get something like: 所以我的问题是我如何重新采样上面形成的组名称并用None填充不存在的组来获得类似的东西:

2016-06-15 08:05:00
    2016-06-15 08:09:26.212962
2016-06-15 08:10:00
    2016-06-15 08:10:13.863304
    2016-06-15 08:11:02.236033
    2016-06-15 08:11:52.085754
2016-06-15 08:15:00
2016-06-15 08:20:00
2016-06-15 08:25:00
    2016-06-15 08:25:41.827770

Can this be formed as a Dataframe as well? 这可以形成为数据帧吗?

Regards 问候

Simplest way is to form them into another DataFrame. 最简单的方法是将它们组成另一个DataFrame。 Use pd.concat 使用pd.concat

frames, names = [], []

grouped = df.groupby(pd.TimeGrouper("5Min"), as_index=False)
for name, group in grouped:
    names.extend([name])
    frames.extend([group])

pd.concat(frames, keys=names)

This is the best I could come up with for now. 这是我现在能想到的最好的。

df.set_index('Time').groupby(pd.TimeGrouper('5T')) \
    .apply(lambda df: df.reset_index()).unstack() \
    .resample('5T').last().stack(dropna=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM