Python 删除多级别索引的名称
我创建了多级数据帧:Python 删除多级别索引的名称,python,pandas,Python,Pandas,我创建了多级数据帧: Price Country England Germany US sys dis 23 0.8 300.0 300.0 800.0 24 0.8 1600.0 600.0 600.0 27 1.0 4000.0 4000.0 5500.0 30 1.0 1000.0 3000.0 1000.0 现在我想删除名称:Country,并将索引从0添加到 Price
Price
Country England Germany US
sys dis
23 0.8 300.0 300.0 800.0
24 0.8 1600.0 600.0 600.0
27 1.0 4000.0 4000.0 5500.0
30 1.0 1000.0 3000.0 1000.0
现在我想删除名称:Country,并将索引从0添加到
Price
sys dis England Germany US
0 23 0.8 300.0 300.0 800.0
1 24 0.8 1600.0 600.0 600.0
2 27 1.0 4000.0 4000.0 5500.0
3 30 1.0 1000.0 3000.0 1000.0
这是我的代码:
df = pd.DataFrame({'sys':[23,24,27,30],'dis': [0.8, 0.8, 1.0,1.0], 'Country':['US', 'England', 'US', 'Germany'], 'Price':[500, 1000, 1500, 2000]})
df = df.set_index(['sys','dis', 'Country']).unstack().fillna(0)
我能得到一些解决方法的提示吗?我对多级数据帧没有太多经验 用于索引
df.reset_index(inplace=True)
对于列
df.columns = df.columns.droplevel(1)
对于索引
df.reset_index(inplace=True)
对于列
df.columns = df.columns.droplevel(1)
我现在最好的选择是:
df.rename_axis([None, None], 1).reset_index()
我现在最好的选择是:
df.rename_axis([None, None], 1).reset_index()
试试这个:
df.reset_index()
df.columns.names =[None, None]
df.columns
MultiIndex(levels=[[u'Price'], [u'England', u'Germany', u'US']],
labels=[[0, 0, 0], [0, 1, 2]],
names=[None, u'Country'])
试试这个:
df.reset_index()
df.columns.names =[None, None]
df.columns
MultiIndex(levels=[[u'Price'], [u'England', u'Germany', u'US']],
labels=[[0, 0, 0], [0, 1, 2]],
names=[None, u'Country'])
当我使用df.columns=df.columns.droplevel1时,标题被Price、Price、Price替换。我可以使用重命名功能,但也许有更聪明的方法。祝你好运。有时,您必须编写一些额外的行来详细了解您需要的内容。当我使用df.columns=df.columns.droplevel1时,标题将替换为Price、Price、Price。我可以使用重命名功能,但也许有更聪明的方法。祝你好运。有时你必须写一些额外的行来详细了解你需要什么我不确定我是否正确理解df.columns.names=[None,None]。它用于多级数据帧。我们是否必须使用两次无,因为存在两级数据帧?如果我也想降低价格头呢?我明白了!非常感谢你帮助我我不确定是否正确理解df.columns.names=[None,None]。它用于多级数据帧。我们是否必须使用两次无,因为存在两级数据帧?如果我也想降低价格头呢?我明白了!非常感谢你帮助我