修改下面代码,将dataframe的行索引也一起添加到Excel中import pandas as pd from openpyxl import Workbook from openpyxl.utils.dataframe import dataframe_to_rows data = {'Name': ['John', 'Emma', 'Peter'], 'Age': [25, 28, 30], 'Gender': ['Male', 'Female', 'Male']} df = pd.DataFrame(data) wb = Workbook() ws = wb.active for row in dataframe_to_rows(df, index=False, header=True): ws.append(row) wb.save('data.xlsx')
时间: 2023-09-13 13:03:15 浏览: 180
你可以将下面的代码插入到你的代码中,以添加DataFrame的行索引到Excel中:
```python
# 将索引列添加到DataFrame中
df_with_index = df.reset_index()
# 将DataFrame写入Excel
for row in dataframe_to_rows(df_with_index, index=False, header=True):
ws.append(row)
```
完整的修改后的代码如下所示:
```python
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
data = {'Name': ['John', 'Emma', 'Peter'],
'Age': [25, 28, 30],
'Gender': ['Male', 'Female', 'Male']}
df = pd.DataFrame(data)
# 创建Excel文件和工作表
wb = Workbook()
ws = wb.active
# 将索引列添加到DataFrame中
df_with_index = df.reset_index()
# 将DataFrame写入Excel
for row in dataframe_to_rows(df_with_index, index=False, header=True):
ws.append(row)
# 保存Excel文件
wb.save('data.xlsx')
```
现在,在Excel文件中,你将看到DataFrame的行索引也被添加进去了。希望对你有帮助!
阅读全文