python - 如何隐藏行索引
问题描述
我想将此 DataFrame 写入没有索引值的 xlsx 文件。我该怎么做?
writer=pd.ExcelWriter(r"D:\pandas.xlsx")
today=datetime.datetime.today()
header = pd.MultiIndex.from_product([[today],["name","lastname","age"]])
data=pd.DataFrame(newList, columns=header)
data.to_excel(writer)
writer.save()
结果:
2019-09-16 18:23:20.851291
name lastname age
0 John McBrain 22
1 Patrick Heszke 33
2 Luk Nans 21
我需要:
2019-09-16 18:23:20.851291
name lastname age
John McBrain 22
Patrick Heszke 33
Luk Nans 21
解决方案
这是异常的解决方法:
NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.
调用df.to_excel(writer, index=False)
whendf.columns
是 MultiIndex 时出现的情况。
import numpy as np
import pandas as pd
np.random.seed(2019)
def write_excel(df, path, *args, **kwargs):
"""
Write df as an excel file to path, roughly similar to `df.to_excel` except that it handles
`df` with MultiIndex columns and `index=False`.
"""
writer = pd.ExcelWriter(path)
header = pd.DataFrame(df.columns.to_list()).T
header.to_excel(writer, header=False, *args, **kwargs)
# Avoid the "NotImplementedError: Writing to Excel with MultiIndex columns"
# exception by temporarily changing the columns to a single-level index
orig_columns = df.columns
df.columns = range(len(df.columns))
df.to_excel(
writer, startrow=len(header), header=False, *args, **kwargs
)
df.columns = orig_columns
writer.save()
df = pd.DataFrame(np.random.randint(10, size=(5, 4)), columns=list("ABCD"))
df = df.set_index(list("AB")).unstack("B")
write_excel(df, r"/tmp/pandas.xlsx", sheet_name="Sheet1", index=False)
print(df)
转换 DataFrame df
,:
C D
B 2 5 8 2 5 8
A
0 5.0 NaN NaN 7.0 NaN NaN
6 NaN NaN 0.0 NaN NaN 0.0
7 NaN NaN 5.0 NaN NaN 3.0
8 5.0 4.0 NaN 8.0 0.0 NaN
到一个看起来像的电子表格
推荐阅读
- reactjs - 测试 onclick标签渲染另一种成分酶
- sql - 选择在特定列上具有非重复值的条目(尽管其他列可能具有重复或非重复值)(SQL)
- html - 在 MediaQuery 中,一个元素在达到该宽度之前具有我们为它设置的某个宽度的某个属性是否正常?
- python - 将 Jenkins 输出日志中显示的命令的时间戳写入 .txt 或 .CSV 文件
- deployment - TFS 发布 - 按创建日期/时间的顺序按计划部署多个版本
- c++ - 包装二维网格索引
- python - 如何 webscrape virustotal 以获取结果 python
- c# - unity开发中updata函数的一个问题
- office365 - 启用 ADFS Extranet 智能锁定
- javascript - 获取数据应该存储在一个状态