如何使用熊猫多索引行

时间:2019-08-20 08:50:34

标签: python python-3.x pandas dataframe multi-index

我是熊猫的新手,每当实现我的代码时,第一行索引就会在每一行重复。

我尝试过的是:

pg,ag,inc是数组

cases=['a1','a2','a3']
data={'RED':rg,'GREEN':gg,'BLUE':bb}
stat_index=['HELO','HERE' ]
df=pd.DataFrame(data,pd.MultiIndex.from_product([cases,stat_index]),['RED','GREEN','BLUE'])
df.to_csv("OUT.CSV")

我得到的是:

             RED         GREEN       BLUE
a1  HELO    304.907     286.074     12.498
a1  HERE    508.670     509.784     94.550
a2  HELO    448.974     509.406     56.466
a2  HERE    764.727     432.084     43.462
a3  HELO    412.539     602.001     10.849
a3  HERE    321.9       603.888     78.847

我真正想要的是:

             RED         GREEN       BLUE
a1  HELO    304.907     286.074     12.498
    HERE    508.670     509.784     94.550
a2  HELO    448.974     509.406     56.466
    HERE    764.727     432.084     43.462
a3  HELO    412.539     602.001     10.849
    HERE    321.9       603.888     78.847

1 个答案:

答案 0 :(得分:1)

只有真正需要时才做。

这是预料之中的,因为如果将MulitIndex写入文件会被重复第一级。如果显示MultiIndex with DataFrame,则仅默认情况下不显示。但是,如果将multi_sparse更改为False,则可以检查实际数据:

with pd.option_context('display.multi_sparse', False):
    print (df)
             RED    GREEN    BLUE
a1 HELO  304.907  286.074  12.498
a1 HERE  508.670  509.784  94.550
a2 HELO  448.974  509.406  56.466
a2 HERE  764.727  432.084  43.462
a3 HELO  412.539  602.001  10.849
a3 HERE  321.900  603.888  78.847

主要原因是兼容性,如果将read_csv中的空白使用MulitIndex,则需要预处理。

但是有可能:

a = df.index.get_level_values(0)
df.index = pd.MultiIndex.from_arrays([a.where(a.duplicated(), ''),
                                      df.index.get_level_values(1)])

with pd.option_context('display.multi_sparse', False):
    print (df)
             RED    GREEN    BLUE
   HELO  304.907  286.074  12.498
a1 HERE  508.670  509.784  94.550
   HELO  448.974  509.406  56.466
a2 HERE  764.727  432.084  43.462
   HELO  412.539  602.001  10.849
a3 HERE  321.900  603.888  78.847