大 pandas 数据帧多指数的Reindex亚级 [英] Reindex sublevel of pandas dataframe multiindex

查看:169
本文介绍了大 pandas 数据帧多指数的Reindex亚级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间序列数据框,我想通过试用和测量重新索引。

I have a time series dataframe and I would like to reindex it by Trials and Measurements.

简化,我有这个:

                value
Trial         
    1     0        13
          1         3
          2         4
    2     3       NaN
          4        12
    3     5        34   

我想变成这样: p>

Which I want to turn into this:

                  value
Trial    
    1      0        13
           1         3
           2         4
    2      0       NaN
           1        12
    3      0        34

做这个?

推荐答案

只是昨天,杰出的安迪·海登将这个功能添加到了第0.13版的大熊猫,这将在今天发布。有关使用示例,请参见此处

Just yesterday, the illustrious Andy Hayden added this feature to version 0.13 of pandas, which will be released any day now. See here for usage example he added to the docs.

如果您愿意从源代码安装大熊猫的开发版本,您现在可以使用它。

If you are comfortable installing the development version of pandas from source, you can use it now.

df['Measurements'] = df.reset_index().groupby('Trial').cumcount()

以下代码是相当的,如果不太客气,并且可以在任何最新版本的大熊猫上工作。

The following code is equivalent, if less pithy, and will work on any recent version of pandas.

grouped = df.reset_index().groupby('Trial')
df['Measurements'] = grouped.apply(lambda x: Series(np.arange(len(x)), x.index))

最后, df.set_index(['Trial' ,'Measurements'],inplace = True)以获得所需的结果。

Finally, df.set_index(['Trial', 'Measurements'], inplace=True) to get your desired result.

这篇关于大 pandas 数据帧多指数的Reindex亚级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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