Как преобразовать индекс в столбец в Pandas (с примерами)


Вы можете использовать следующий базовый синтаксис для преобразования индекса кадра данных pandas в столбец:

#convert index to column
df.reset_index(inplace= True )

Если у вас есть DataFrame MultiIndex pandas, вы можете использовать следующий синтаксис для преобразования определенного уровня индекса в столбец:

#convert specific level of MultiIndex to column
df.reset_index(inplace= True , level = ['Level1'])

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: преобразование индекса в столбец

Следующий код показывает, как преобразовать индекс pandas DataFrame в столбец:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
 'assists': [5, 7, 7, 9, 12],
 'rebounds': [11, 8, 10, 6, 6]})

#view DataFrame
df

points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6

#convert index to column
df.reset_index(inplace= True )

#view updated DataFrame
df

 index points assists rebounds
0 0 25 5 11
1 1 12 7 8
2 2 15 7 10
3 3 14 9 6
4 4 19 12 6

Пример 2. Преобразование MultiIndex в столбцы

Предположим, у нас есть следующий DataFrame MultiIndex pandas:

import pandas as pd

#create DataFrame
index_names = pd.MultiIndex.from_tuples([('Level1','Lev1', 'L1'),
('Level2','Lev2', 'L2'),
('Level3','Lev3', 'L3'),
('Level4','Lev4', 'L4')],
 names=['Full','Partial', 'ID'])

data = {' Store': ['A','B','C','D'],
 'Sales': [17, 22, 29, 35]}

df = pd.DataFrame(data, columns = ['Store',' Sales'], index=index_names)

#view DataFrame
df

 Store Sales
Full Partial ID 
Level1 Lev1 L1 A 17
Level2 Lev2 L2 B 22
Level3 Lev3 L3 C 29
Level4 Lev4 L4 D 35

В следующем коде показано, как преобразовать каждый уровень MultiIndex в столбцы в кадре данных pandas:

#convert all levels of index to columns
df.reset_index(inplace= True )

#view updated DataFrame
df

 Full Partial ID Store Sales
0 Level1 Lev1 L1 A 17
1 Level2 Lev2 L2 B 22
2 Level3 Lev3 L3 C 29
3 Level4 Lev4 L4 D 35

Мы также можем использовать следующий код для преобразования определенного уровня MultiIndex в столбец:

#convert just 'ID' index to column in DataFrame
df.reset_index(inplace= True , level = ['ID'])

#view updated DataFrame
df

 ID Store Sales
Full Partial 
Level1 Lev1 L1 A 17
Level2 Lev2 L2 B 22
Level3 Lev3 L3 C 29
Level4 Lev4 L4 D 35

Обратите внимание, что только уровень «ID» был преобразован в столбец в DataFrame.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные функции в pandas:

Как установить столбец в качестве индекса в Pandas
Как удалить столбцы по индексу в Pandas
Как сортировать DataFrame по индексу и столбцу в Pandas