如何将 pandas 数据框的索引转换为列? [英] How to convert index of a pandas dataframe into a column?

查看:112
本文介绍了如何将 pandas 数据框的索引转换为列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很明显,但是我似乎无法弄清楚如何将数据帧的索引转换为列?

This seems rather obvious, but I can't seem to figure out how to convert an index of data frame to a column?

例如:

df=
        gi       ptt_loc
 0  384444683      593  
 1  384444684      594 
 2  384444686      596  

收件人

df=
    index1    gi       ptt_loc
 0  0     384444683      593  
 1  1     384444684      594 
 2  2     384444686      596  

推荐答案

两个:

df['index1'] = df.index

.reset_index :

df.reset_index(level=0, inplace=True)


因此,如果您有一个包含3个索引级别的多索引框架,例如:


so, if you have a multi-index frame with 3 levels of index, like:

>>> df
                       val
tick       tag obs        
2016-02-26 C   2    0.0139
2016-02-27 A   2    0.5577
2016-02-28 C   6    0.0303

,并且要将索引中的第一级(tick)和第三级(obs)转换为列,您可以这样做:

and you want to convert the 1st (tick) and 3rd (obs) levels in the index into columns, you would do:

>>> df.reset_index(level=['tick', 'obs'])
          tick  obs     val
tag                        
C   2016-02-26    2  0.0139
A   2016-02-27    2  0.5577
C   2016-02-28    6  0.0303

这篇关于如何将 pandas 数据框的索引转换为列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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