我有一个这种类型的数据框:
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
有什么帮助吗?
最佳答案
您可以通过索引选择元组的每个值,最后按 DataFrame.reset_index
创建默认索引与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
另一个想法是创建新的DataFrame
并连接到原始数据:
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
另一个想法是通过MultiIndex.from_tuples
创建MultiIndex
:
df.index = pd.MultiIndex.from_tuples(df.index, names=['year','class'])
print (df)
a
year class
2010 1 100
2 150
2011 1 180
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
关于python - 拆分 pandas 数据帧索引中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55123643/