如何在Pandas Pivot_table中填充索引

时间:2017-05-26 06:48:15

标签: pandas pivot-table

我使用pandas.pivot_table显示以下DataFrame:

A  B
a    SH     1.0
b    BJ     2.0
     SH     3.0
c    BJ    10.0
     SH     5.0

所以我想将DataFrame更改为以下内容,我的意思是填写 索引中的空白:

A  B
a    SH     1.0
b    BJ     2.0
b    SH     3.0
c    BJ    10.0
c    SH     5.0

1 个答案:

答案 0 :(得分:0)

没有必要,只有pandas以这种方式显示MultiIndex

您可以按multi_sparse

进行更改
#temporaly display it
with pd.option_context('display.multi_sparse', False):
    print (df)

A  B 
a  SH     1.0
b  BJ     2.0
b  SH     3.0
c  BJ    10.0
c  SH     5.0
Name: C, dtype: float64

为了写入excel,将连接的单元格组合在一起:

df.to_excel('file.xlsx')

one

可能的解决方案是reset_index,然后不按index=False编写默认索引:

df.reset_index().to_excel('file.xlsx', index=False)

two

相关问题