How to convert index of a pandas dataframe into a column

How to convert an index of a dataframe into a column?

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> gi ptt_loc
0 384444683 593
1 384444684 594
2 384444686 596
</code>
<code> gi ptt_loc 0 384444683 593 1 384444684 594 2 384444686 596 </code>
        gi       ptt_loc
 0  384444683      593  
 1  384444684      594 
 2  384444686      596  

to

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> index1 gi ptt_loc
0 0 384444683 593
1 1 384444684 594
2 2 384444686 596
</code>
<code> index1 gi ptt_loc 0 0 384444683 593 1 1 384444684 594 2 2 384444686 596 </code>
    index1    gi       ptt_loc
 0  0     384444683      593  
 1  1     384444684      594 
 2  2     384444686      596  

1

either:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df['index1'] = df.index
</code>
<code>df['index1'] = df.index </code>
df['index1'] = df.index

or .reset_index:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = df.reset_index()
</code>
<code>df = df.reset_index() </code>
df = df.reset_index()

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> 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
</code>
<code>>>> 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 </code>
>>> 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

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> 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
</code>
<code>>>> 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 </code>
>>> 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

1

rename_axis + reset_index

You can first rename your index to a desired label, then elevate to a series:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = df.rename_axis('index1').reset_index()
print(df)
index1 gi ptt_loc
0 0 384444683 593
1 1 384444684 594
2 2 384444686 596
</code>
<code>df = df.rename_axis('index1').reset_index() print(df) index1 gi ptt_loc 0 0 384444683 593 1 1 384444684 594 2 2 384444686 596 </code>
df = df.rename_axis('index1').reset_index()

print(df)

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

This works also for MultiIndex dataframes:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>print(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
df = df.rename_axis(['index1', 'index2', 'index3']).reset_index()
print(df)
index1 index2 index3 val
0 2016-02-26 C 2 0.0139
1 2016-02-27 A 2 0.5577
2 2016-02-28 C 6 0.0303
</code>
<code>print(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 df = df.rename_axis(['index1', 'index2', 'index3']).reset_index() print(df) index1 index2 index3 val 0 2016-02-26 C 2 0.0139 1 2016-02-27 A 2 0.5577 2 2016-02-28 C 6 0.0303 </code>
print(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

df = df.rename_axis(['index1', 'index2', 'index3']).reset_index()

print(df)

       index1 index2  index3     val
0  2016-02-26      C       2  0.0139
1  2016-02-27      A       2  0.5577
2  2016-02-28      C       6  0.0303

0

To provide a bit more clarity, let’s look at a DataFrame with two levels in its index (a MultiIndex).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'],
['North', 'South']],
names=['State', 'Direction'])
df = pd.DataFrame(index=index,
data=np.random.randint(0, 10, (6,4)),
columns=list('abcd'))
</code>
<code>index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'], ['North', 'South']], names=['State', 'Direction']) df = pd.DataFrame(index=index, data=np.random.randint(0, 10, (6,4)), columns=list('abcd')) </code>
index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'], 
                                    ['North', 'South']], 
                                   names=['State', 'Direction'])

df = pd.DataFrame(index=index, 
                  data=np.random.randint(0, 10, (6,4)), 
                  columns=list('abcd'))

enter image description here

The reset_index method, called with the default parameters, converts all index levels to columns and uses a simple RangeIndex as new index.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df.reset_index()
</code>
<code>df.reset_index() </code>
df.reset_index()

enter image description here

Use the level parameter to control which index levels are converted into columns. If possible, use the level name, which is more explicit. If there are no level names, you can refer to each level by its integer location, which begin at 0 from the outside. You can use a scalar value here or a list of all the indexes you would like to reset.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df.reset_index(level='State') # same as df.reset_index(level=0)
</code>
<code>df.reset_index(level='State') # same as df.reset_index(level=0) </code>
df.reset_index(level='State') # same as df.reset_index(level=0)

enter image description here

In the rare event that you want to preserve the index and turn the index into a column, you can do the following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># for a single level
df.assign(State=df.index.get_level_values('State'))
# for all levels
df.assign(**df.index.to_frame())
</code>
<code># for a single level df.assign(State=df.index.get_level_values('State')) # for all levels df.assign(**df.index.to_frame()) </code>
# for a single level
df.assign(State=df.index.get_level_values('State'))

# for all levels
df.assign(**df.index.to_frame())

0

For MultiIndex you can extract its subindex using

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df['si_name'] = R.index.get_level_values('si_name')
</code>
<code>df['si_name'] = R.index.get_level_values('si_name') </code>
df['si_name'] = R.index.get_level_values('si_name') 

where si_name is the name of the subindex.

0

If you want to use the reset_index method and also preserve your existing index you should use:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df.reset_index().set_index('index', drop=False)
</code>
<code>df.reset_index().set_index('index', drop=False) </code>
df.reset_index().set_index('index', drop=False)

or to change it in place:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
</code>
<code>df.reset_index(inplace=True) df.set_index('index', drop=False, inplace=True) </code>
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
</code>
<code>print(df) gi ptt_loc 0 384444683 593 4 384444684 594 9 384444686 596 print(df.reset_index()) index gi ptt_loc 0 0 384444683 593 1 4 384444684 594 2 9 384444686 596 print(df.reset_index().set_index('index', drop=False)) index gi ptt_loc index 0 0 384444683 593 4 4 384444684 594 9 9 384444686 596 </code>
print(df)
          gi  ptt_loc
0  384444683      593
4  384444684      594
9  384444686      596

print(df.reset_index())
   index         gi  ptt_loc
0      0  384444683      593
1      4  384444684      594
2      9  384444686      596

print(df.reset_index().set_index('index', drop=False))
       index         gi  ptt_loc
index
0          0  384444683      593
4          4  384444684      594
9          9  384444686      596

And if you want to get rid of the index label you can do:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
</code>
<code>df2 = df.reset_index().set_index('index', drop=False) df2.index.name = None print(df2) index gi ptt_loc 0 0 384444683 593 4 4 384444684 594 9 9 384444686 596 </code>
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
   index         gi  ptt_loc
0      0  384444683      593
4      4  384444684      594
9      9  384444686      596

This should do the trick (if not multilevel indexing)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df.reset_index().rename({'index':'index1'}, axis = 'columns')
</code>
<code>df.reset_index().rename({'index':'index1'}, axis = 'columns') </code>
df.reset_index().rename({'index':'index1'}, axis = 'columns')

Code Result

And of course, you can always set inplace = True, if you do not want to assign this to a new variable in the function parameter of rename.

0

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1
new gi ptt
0 0 232 342
1 1 66 56
2 2 34 662
3 3 43 123
</code>
<code>df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]}) p = df1.index.values df1.insert( 0, column="new",value = p) df1 new gi ptt 0 0 232 342 1 1 66 56 2 2 34 662 3 3 43 123 </code>
df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1

    new     gi     ptt
0    0      232    342
1    1      66     56 
2    2      34     662
3    3      43     123

2

To retain the index (that was converted into a column) as index, use a combination of to_frame() and join(). In particular, this doesn’t produce a SettingWithCopyWarning, unlike assignment.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = df.index.to_frame(name='A').join(df)
</code>
<code>df = df.index.to_frame(name='A').join(df) </code>
df = df.index.to_frame(name='A').join(df)

res1

This works for MultiIndex, too.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = df.index.to_frame(name=['A', 'B']).join(df)
</code>
<code>df = df.index.to_frame(name=['A', 'B']).join(df) </code>
df = df.index.to_frame(name=['A', 'B']).join(df)

Also, as Quinten mentions, since pandas 1.5.0, rename_axis + reset_index (or reset_index + rename) syntax have become obsolete. You can directly pass names= as an argument to reset_index(). Even duplicate column names are allowed if allow_duplicates=True is passed (although having duplicate column labels is highly unadvisable).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = df.reset_index(names=['A', 'B'])
</code>
<code>df = df.reset_index(names=['A', 'B']) </code>
df = df.reset_index(names=['A', 'B'])

res2

I usually do it this way:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = df.assign(index1=df.index)
</code>
<code>df = df.assign(index1=df.index) </code>
df = df.assign(index1=df.index)

1

In the newest version of pandas 1.5.0, you could use the function reset_index with the new argument names to specify a list of names you want to give the index columns. Here is a reproducible example with one index column:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import pandas as pd
df = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
gi ptt
0 232 342
1 66 56
2 34 662
3 43 123
df.reset_index(names=['new'])
</code>
<code>import pandas as pd df = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]}) gi ptt 0 232 342 1 66 56 2 34 662 3 43 123 df.reset_index(names=['new']) </code>
import pandas as pd

df = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})

    gi  ptt
0  232  342
1   66   56
2   34  662
3   43  123

df.reset_index(names=['new'])

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> new gi ptt
0 0 232 342
1 1 66 56
2 2 34 662
3 3 43 123
</code>
<code> new gi ptt 0 0 232 342 1 1 66 56 2 2 34 662 3 3 43 123 </code>
   new   gi  ptt
0    0  232  342
1    1   66   56
2    2   34  662
3    3   43  123

This can also easily be applied with MultiIndex. Just create a list of the names you want.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật