shr*_*tti 5 python multi-index pandas 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')
Run Code Online (Sandbox Code Playgroud)
现在如何摆脱第一列。
即使我没有提到index=['A', 'B', 'C'] 或names=['first', 'second']
默认情况下会创建index=[0, 1, 2]
那么如何在创建 Excel 时删除第一列。
这是 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)
Run Code Online (Sandbox Code Playgroud)
在上述代码之后添加新的 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
Run Code Online (Sandbox Code Playgroud)
稍后写下,就像你正在做的那样 -
# Writing to excel file keeping index
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test1')
Run Code Online (Sandbox Code Playgroud)
注意 - 有一个小缺点,单元格A1和单元B1格没有合并。