pandas将数据写入excel并保留原来数据
时间: 2023-08-27 13:05:08 浏览: 773
你可以使用 pandas 的 `ExcelWriter` 对象和 `append` 参数来实现将数据追加写入 Excel 文件并保留原来的数据。
首先,你需要创建一个 `ExcelWriter` 对象,并使用 `pd.read_excel()` 方法读取原始 Excel 文件中的数据:
```python
import pandas as pd
# 读取原始 Excel 文件中的数据
df_old = pd.read_excel('original_file.xlsx')
# 创建 ExcelWriter 对象
writer = pd.ExcelWriter('updated_file.xlsx', engine='xlsxwriter')
```
接下来,你可以使用 `to_excel()` 方法将新数据写入 Excel 文件,同时使用 `append` 参数保留原来的数据:
```python
# 将新数据写入 Excel 文件
df_new.to_excel(writer, sheet_name='Sheet1', startrow=len(df_old)+1, header=False, index=False)
# 保存 Excel 文件
writer.save()
```
在上面的代码中,`startrow` 参数指定新数据写入的起始行,为原始数据的长度加1;`header` 参数设置为 `False` 表示不写入新数据的列名;`index` 参数设置为 `False` 表示不写入新数据的行索引。
这样,新数据就会被追加写入 Excel 文件中,同时原来的数据也会被保留。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)