用pandas给excel源数据首行前添加一列
时间: 2024-05-11 08:14:05 浏览: 97
基于pandas向csv添加新的行和列
假设excel源数据名称为"source.xlsx",首行为"A1"至"N1",要在首行前添加一列"ID",可以按照以下步骤操作:
1. 导入pandas库并读取excel源数据:
```python
import pandas as pd
df = pd.read_excel('source.xlsx', header=0)
```
2. 添加新列"ID",并将其值设置为首行前的序号:
```python
df.insert(0, 'ID', range(1, len(df)+1))
```
3. 将新数据写回到excel源文件中:
```python
writer = pd.ExcelWriter('source.xlsx')
df.to_excel(writer, index=False)
writer.save()
```
完整代码如下:
```python
import pandas as pd
# 读取excel源数据
df = pd.read_excel('source.xlsx', header=0)
# 添加新列"ID",并将其值设置为首行前的序号
df.insert(0, 'ID', range(1, len(df)+1))
# 将新数据写回到excel源文件中
writer = pd.ExcelWriter('source.xlsx')
df.to_excel(writer, index=False)
writer.save()
```
阅读全文