如何在Python中使用MultiIndex和to_excel时使index = False或摆脱第一列

时间:2019-02-27 05:37:43

标签: python pandas multi-index xlsxwriter

这是代码示例:

import numpy as np
import pandas as pd
import xlsxwriter

tuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')]

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]

pd.MultiIndex.from_product(iterables, names=['first', 'second'])

df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)

print(df)

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test1')

创建的excel输出:enter image description here

现在如何摆脱第一列。

即使我不提到index = ['A','B','C']或names = ['first','second']

默认情况下,它会创建index = [0,1,2]

所以在创建Excel时如何摆脱第一列。

1 个答案:

答案 0 :(得分:1)

这里有5行修正-

原始代码-

tuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')]
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
df = pd.DataFrame(np.random.randn(3, 8), columns=index) 

在上述代码后将添加5行-

# Setting first column as index
df = df.set_index(('bar', 'one'))

# Removing 'bar', 'one' frm index name
df.index.name = ''

# Setting new columns Multiindex
tuples = [('', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')]
index_new = pd.MultiIndex.from_tuples(tuples, names=['bar', 'one'])
df.columns = index_new

以后按您的经验写成excel-

# Writing to excel file keeping index
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test1')

img

注意-单元格A1B1不合并是一个小缺点。