2 回答
TA贡献1765条经验 获得超5个赞
请参阅文档中的以下部分:df.to_excel()
如果要写入工作簿中的多个工作表,则必须指定一个 ExcelWriter 对象:
df2 = df1.copy()
with pd.ExcelWriter('output.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet_name_1')
df2.to_excel(writer, sheet_name='Sheet_name_2')
因此,您可能需要退出循环。writer.save()
TA贡献1811条经验 获得超4个赞
我不能代表你的代码,因为我不能运行它,“filter_text”似乎是你编写但不包括的函数。
基本上你有两个错误之一,我可以看到,
首先,不清楚您在哪里初始化对象。writer
第二,你用每个循环覆盖工作表 - 将其移动到循环之外。
pd.ExcelFile可以用作上下文管理器 - 因此您需要关闭/保存它。
def close(self):
"""synonym for save, to make it more file-like"""
return self.save()
writer = pd.ExcelWriter('file.xlsx')
for sub in sublocation_ids:
city_num_int = sub['id']
city_num_str = str(city_num_int)
city_name = sub['name']
filter_text_new = filter_text.format(city_num_str)
data = json.dumps({"filters": [filter_text_new], "sort_by":"created_at", "size":2})
r = requests.post(url = api_endpoint, data = data).json()
articles_list = r["articles"]
articles_list_normalized = json_normalize(articles_list)
df = articles_list_normalized
df['publication_timestamp'] = pd.to_datetime(df['publication_timestamp'])
df['publication_timestamp'] = df['publication_timestamp'].apply(lambda x: x.now().strftime('%Y-%m-%d'))
df.to_excel(writer, sheet_name = city_name)
writer.save() # move this after you've finished writing to your writer object.
表格作为字典
如果您对类的内部感到好奇,请在对象上使用,以便您可以看到元数据。.__dict__.
writer = pd.ExcelWriter('file.xlsx')
df.to_excel(writer,sheet_name='Sheet1')
df.to_excel(writer,sheet_name='Sheet2')
print(writer.__dict__)
{'path': 'file.xlsx',
'sheets': {'Sheet1': <xlsxwriter.worksheet.Worksheet at 0x11a05a79a88>,
'Sheet2': <xlsxwriter.worksheet.Worksheet at 0x11a065218c8>},
'cur_sheet': None,
'date_format': 'YYYY-MM-DD',
'datetime_format': 'YYYY-MM-DD HH:MM:SS',
'mode': 'w',
'book': <xlsxwriter.workbook.Workbook at 0x11a064ff1c8>}
添加回答
举报