无法使用熊猫存储多索引csv文件

问题描述 投票:0回答:1

我有一个看起来像的数据框,

                         JAPE_feature                     
                     100 200 2200 2600 4600         
did offset word                                                               
0   0      aa          0   1    0    0    0          
0   11     bf          0   1    0    0    0           
0   12     vf          0   1    0    0    0             
0   13     rw          1   0    0    0    0             
0   14     asd         1   0    0    0    0               
0   16     dsdd        0   0    1    0    0               
0   18     wd          0   0    0    1    0              
0   20     wsw         0   0    0    1    0               
0   21     sd          0   0    0    0    1

现在,我在这里尝试以csv格式保存此数据帧。

df.to_csv('data.csv')

所以,它的存储方式是,

enter image description here

现在,在这里我试图保存而不在JAPE_feature列中创建新列。它只会在一列中包含5个子功能。

         JAPE_FEATURES
   100 |  200 |  2200 |   2600 | 4600 

the sub-columns should be like this . It should not create the different columns 
python python-3.x pandas
1个回答
0
投票

我认为这里最好是将DataFrame转换为excel,如果需要merge MultiIndex in columns的第一级:

df.to_excel('data.xlsx')

如果要csv则有问题,有必要将MultiIndex更改为将重复值替换为空字符串:

print (df.columns)
MultiIndex([('JAPE_feature',  100),
            ('JAPE_feature',  200),
            ('JAPE_feature', 2200),
            ('JAPE_feature', 2600),
            ('JAPE_feature', 4600)],
           )

cols = df.columns.to_frame()
cols[0] = cols[0].mask(cols[0].duplicated(), '')
df.columns = pd.MultiIndex.from_arrays([cols[0], cols[1]])
print (df.columns)
MultiIndex([('JAPE_feature',  100),
            (            '',  200),
            (            '', 2200),
            (            '', 2600),
            (            '', 4600)],
           names=[0, 1])

df.to_csv('data.csv')
© www.soinside.com 2019 - 2024. All rights reserved.