Python 在数据帧的索引中拆分值

Python 在数据帧的索引中拆分值,python,pandas,split,Python,Pandas,Split,我有一个这种类型的数据帧: d = {'a': [100,150,180,190]} df = pd.DataFrame(data=d, index=[(2010,1) ,(2010,2 ), (2011,1) ,(2011,2 )]) 返回 Out[91]: a (2010, 1) 100 (2010, 2) 150 (2011, 1) 180 (2011, 2) 190 我的工作范围是分割索引中的值,并通过保留索引的信息使数据帧更具可读性。换句话说,我

我有一个这种类型的数据帧:

d = {'a': [100,150,180,190]}
df = pd.DataFrame(data=d, index=[(2010,1) ,(2010,2 ), (2011,1) ,(2011,2 )])
返回

Out[91]: 
             a
(2010, 1)  100
(2010, 2)  150
(2011, 1)  180
(2011, 2)  190
我的工作范围是分割索引中的值,并通过保留索引的信息使数据帧更具可读性。换句话说,我的预期结果是:

dd = {'a': [100,150,180,190], 'year': [2010, 2011, 2010,2011], 'class': [1,2, 1,2]}
df2 = pd.DataFrame(data=dd)

Out[92]: 
     a  year  class
0  100  2010      1
1  150  2011      2
2  180  2010      1
3  190  2011      2

有什么帮助吗

您可以通过索引选择元组的每个值,并使用
drop=True上次创建默认索引:

df['year'] = df.index.str[0]
df['class'] = df.index.str[1]
df = df.reset_index(drop=True)
print (df)
     a  year  class
0  100  2010      1
1  150  2010      2
2  180  2011      1
3  190  2011      2
另一个想法是创建新的
数据帧
,并连接到原始数据帧:

df1 = pd.DataFrame(df.index.tolist(), columns=['year','class'], index=df.index)
df = df.join(df1).reset_index(drop=True)
print (df)
     a  year  class
0  100  2010      1
1  150  2010      2
2  180  2011      1
3  190  2011      2
另一个想法是通过以下方式创建多索引:

然后创建可能的列:

df = df.reset_index()
print (df)
   year  class    a
0  2010      1  100
1  2010      2  150
2  2011      1  180
3  2011      2  190
df = df.reset_index()
print (df)
   year  class    a
0  2010      1  100
1  2010      2  150
2  2011      1  180
3  2011      2  190