也许您可以通过使用MultiIndex获得最佳效果:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(8).reshape(4,2), index=['a_1', 'b_2', 'c_3', 'c_4'])
print(df)
index = pd.MultiIndex.from_tuples([item.split('_') for item in df.index])
df.index = index
print(df)
这样,您可以根据索引的第一级访问内容:
In [30]: df.ix['c']
Out[30]:
0 1
3 4 5
4 6 7
或根据指数的两个级别:
In [31]: df.ix[('c','3')]
Out[31]:
0 4
1 5
Name: (c, 3)
此外,所有DataFrame的方法都被设计为与带有MultiIndices的DataFrames一起使用,所以您不会失去任何东西。
但是,如果您真的想要删除索引的第二级,可以这样做:
df.reset_index(level=1, drop=True, inplace=True)
print(df)