[英]How to skip the default data frame index, when printing a python data frame in an excel worksheet, using openpyxl
I am trying to print a pandas data frame in an excel sheet, using openpyxl.我正在尝试使用 openpyxl 在 excel 表中打印 pandas 数据框。 Until now I have accomplished to print the data frame with the default index.
到目前为止,我已经完成了使用默认索引打印数据框。 My question is, how to print it without the default index.
我的问题是,如何在没有默认索引的情况下打印它。 The following example script generates Table 1 and I would like to know what I need to modify in order to come up with Table 2 .
以下示例脚本生成表 1 ,我想知道我需要修改什么才能得出表 2 。
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
df = pd.DataFrame((1,2,3,4,5,6))
wb = openpyxl.Workbook()
sheet = wb.active
rows = dataframe_to_rows(df)
for r_idx, row in enumerate(rows, 1):
for c_idx, value in enumerate(row, 1):
sheet.cell(row=r_idx+1, column=c_idx, value=value)
wb.save('book1.xlsx')
Table 1表格1
0
0 1
1 2
2 3
3 4
4 5
5 6
Table 2表 2
1
2
3
4
5
6
Unless you have a more elaborated requirement, it's quite easier to go straight with pandas.DataFrame.to_excel
, which already integrates with openpyxl
.除非您有更详细的要求,否则 go 直接使用
pandas.DataFrame.to_excel
更容易,它已经与openpyxl
集成
df.to_excel('book1.xlsx')
To drop the index, just add:要删除索引,只需添加:
df.to_excel('book1.xlsx', index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.