Make column from pandas dataframe index

心不动则不痛 提交于 2019-12-10 17:26:35

问题


I have a dataframe where I would like to turn the data in the (first level of the) index into a column. Practically my df looks like this:

         col1
CoI     
 AK   0     1
      1    31
      2   NaN 
 BB   0     5
      1    31
      2   NaN 

And I would like to turn it into this:

      col1  CoI

   0     1   AK
   1    31   AK
   2   NaN   AK
   0     5   BB
   1    31   BB
   2   NaN   BB

How can I best do this? I think this is a rather basic functionality, but as with many other "basic" pandas things I cannot find info on this anywhere.

Many Thanks,


回答1:


df.reset_index(level=0, inplace=True) should do it. See the docs here.



来源:https://stackoverflow.com/questions/20228998/make-column-from-pandas-dataframe-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!