python - 删除多级索引的名称

标签 python pandas

我创建了多级 DataFrame:

         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)

我可以提供一些解决方法的提示吗?我对多级 DataFrame 没有太多经验。

最佳答案

试试这个:

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'])

关于python - 删除多级索引的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38878885/

相关文章:

python - 复合类型和标量类型的生命周期有什么区别?

python - 导入时,为什么只指定了特定部分却加载了整个模块?

java - 使用 Eclipse 导入 py4j

python - 如何从 tsv 文件中找到所有节点三元组(大小为 3 的连通分量)?

python - Pandas - 如果行包含相同的值,如何匹配行

python - 使用 Python 在嵌套字典中查找键

python optimize.leastsq : fitting a circle to 3d set of points

python - 如何在 Python 中删除日期相同的数据

python - 未知的字符串格式,python 错误

python - 嵌套 for 循环字典存储值 python nsepy