你可以使用下面的基本语法来将pandas DataFrame的索引转换为一个列:
#convert index to column
df.reset_index(inplace=True)
如果你有一个MultiIndex pandas DataFrame,你可以使用下面的语法将特定级别的索引转换为一个列:
#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的pandas DataFrame:
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 DataFrame中的列:
#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中按索引删除列
如何在Pandas中按索引和列对DataFrame进行排序