python - 在 Python 中使用 MultiIndex 和 to_excel 时如何使 index=False 或删除第一列
问题描述
这是代码示例:
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')
现在如何摆脱第一列。
即使我没有提到 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)
在上述代码之后添加新的 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')
A1
注意 - 单元格B1
没有合并只有一个小缺点。
推荐阅读
- scala - 如何找出cats.Parallel的函子?
- java - 如何计算字符串中出现的字符串次数(有重叠)
- tsql - 如何从 SSRS 函数代码执行 SQL Server 存储过程
- python - 在 python 记录器中做相当于 log_struct
- javascript - 达到到期日期后不显示 Javascript
- javascript - 如何为这个多维数组创建必要的函数?
- microsoft-edge - 更改 Edge 允许的最大同时 TCP 连接数
- go - 如何从我的控制器文件向本地 Kubernetes 部署的服务提供静态文件?
- javascript - 如何防止跳过的测试被检入源代码控制
- swift - 如何使用 URLSession 从 HTTP 请求的 JSON 对象中获取特定属性