我创建了一个webscraper,该Webscraper通过chrome驱动程序提取数据,将其放入数据框,然后打印所有值。为了进行一些趋势分析,我计划每天运行代码5次。因此,我想通过在每个周期中创建一个新表将数据放入excel。
我的数据是数据框格式。我的问题源于:
使用openpyxl-无法输入以下代码中引用的df格式
使用大熊猫-工作表1中的数据已被覆盖。我希望每张工作表都具有运行时间的时间戳,但这会完全覆盖。
所以我的看法是,我可以让熊猫在每个运行周期内添加一个新工作簿(即添加一个新工作表并将数据附加到那里),或者我需要找出一种方法来将df放入openpyxl格式。
from datetime import datetime
import pandas as pd
import numpy as np
path = r"C:\\Users\\Jacob\\Documents\\MyStuff\\weather.xlsx"
now = datetime.now()
j = now.strftime("%m-%d, %H.%M.%S")
x1 = all_weather
df1 = pd.DataFrame(x1)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = str(j))
writer.save()
writer.close()
OR
book = load_workbook('C:\\Users\\Jacob\\Documents\\MyStuff\\weather.xlsx')
now = datetime.now()
j = now.strftime("%m-%d, %H.%M.%S")
sheet = book.create_sheet(str(j))
sheet.append(weather_df)
使用openpyxl时
TypeError:值必须是列表,元组,范围或生成器或字典。提供的值为
使用熊猫时 每次都被覆盖。
答案 0 :(得分:1)
我个人建议使用xslxwriter而不是openpyxl。
但是您应该使用pandas to_excel(),而不是使用另一个模块创建一个新工作表并将数据框附加到该工作表。所以看起来更像
weather_df.to_excel("path_to_excel_file.xlsx",sheet_name = "sheet name here")