复杂的枢轴和重采样 [英] Complex pivot and resample

查看:80
本文介绍了复杂的枢轴和重采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定从哪里开始,所以对我的尝试不足表示歉意.

I'm not sure where to start with this so apologies for my lack of an attempt.

这是我的数据的初始形状:

This is the initial shape of my data:

df = pd.DataFrame({
    'Year-Mth': ['1900-01'
                 ,'1901-02'
                 ,'1903-02'
                 ,'1903-03'
                 ,'1903-04'
                 ,'1911-08'
                 ,'1911-09'], 
    'Category': ['A','A','B','B','B','B','B'], 
    'SubCategory': ['X','Y','Y','Y','Z','Q','Y'], 
    'counter': [1,1,1,1,1,1,1]
})

df

这是我想要得到的结果-以下第M年已重新采样到4年时段:

This is the result I'd like to get to - the Mth-Year in the below has been resampled to 4 year buckets:

如果可能的话,我想通过一种可重用"Year-Mth"的过程来做到这一点-这样我就可以轻松地切换到不同的存储桶.

If possible I'd like to do this via a process that makes 'Year-Mth' resamplable - so I can easily switch to different buckets.

推荐答案

cols = [df.SubCategory, pd.to_datetime(df['Year-Mth']), df.Category]
df1 = df.set_index(cols).counter

df1.unstack('Year-Mth').T.resample('60M', how='sum').stack(0).swaplevel(0, 1).sort_index().fillna('')

这篇关于复杂的枢轴和重采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆