简体   繁体   English

Python 创建数据并将数据附加到新的 excel 工作簿熊猫

[英]Python creating and appending data to new excel workbook pandas

I have created a webscraper that pulls data from thru chrome driver, puts it into a dataframe, and prints all the values.我创建了一个 webscraper,它从 chrome 驱动程序中提取数据,将其放入数据帧中,并打印所有值。 In order to do some trend analysis, I plan to run the code 5 times a day each day.为了做一些趋势分析,我计划每天运行代码 5 次。 Therefore I want to put the data into excel by creating a new sheet during each cycle.因此,我想通过在每个周期中创建一个新工作表来将数据放入 excel 中。

My data is in a dataframe format.我的数据采用数据帧格式。 My issue stems from:我的问题源于:

Using openpyxl - cannot input the df format referenced in the code below使用 openpyxl - 无法输入以下代码中引用的 df 格式

Using pandas - the data has been getting overwritten in sheet 1. I want each sheet to have a timestamp of when it ran, but this completely overwrites.使用 Pandas - 数据已在工作表 1 中被覆盖。我希望每张工作表都有一个运行时间的时间戳,但这会完全覆盖。

So the way I see it, I can either get pandas to add a new workbook during each run cycle (ie adding a new sheet and appending the data there) or I need to figure out a way to get the df into openpyxl format.所以在我看来,我可以让 Pandas 在每个运行周期中添加一个新工作簿(即添加一个新工作表并在那里附加数据),或者我需要找出一种方法将 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)

When using openpyxl使用 openpyxl 时

TypeError: Value must be a list, tuple, range or generator, or a dict.类型错误:值必须是列表、元组、范围或生成器,或字典。 Supplied value is提供的值为

When using pandas sheet gets overwritten each time.每次使用熊猫表时都会被覆盖。

I personally recommend using xslxwriter instead of openpyxl.我个人推荐使用xslxwriter而不是 openpyxl。

But you should use pandas to_excel() rather then creating a new sheet with another module and appending a dataframe to that sheet.但是您应该使用 pandas to_excel()而不是使用另一个模块创建一个新工作表并将数据附加到该工作表。 So it would look more like所以它看起来更像

weather_df.to_excel("path_to_excel_file.xlsx",sheet_name = "sheet name here")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM