亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

蟒蛇熊貓沒有在Excel文件中創建多個選項卡?

蟒蛇熊貓沒有在Excel文件中創建多個選項卡?

一只甜甜圈 2022-09-27 16:13:19
我有一個從第三方API中提取的python腳本。該腳本循環運行 3 個不同的城市,并為每個城市創建一個數據框。然后,我將數據框作為選項卡傳輸到Excel工作表中。下面是代碼。    sublocation_ids = [                {                  "id": 163,                  "name": "Atlanta, GA"                },                {                  "id": 140,                  "name": "Austin, TX"                },                {                  "id": 164,                  "name": "Baltimore, MD"                }              ]filter_text = "(headline:coronavirus OR summary:coronavirus OR headline:covid-19 OR summary:covid-19) AND categories:{}"writer = pd.ExcelWriter(excel_path)    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()我面臨的當前問題是,只有一個選項卡是在excel工作表中創建的,用于我從API中提取數據的第一個城市“亞特蘭大,GA”。如何為目錄中的每個城市創建選項卡,或者我的代碼是否有任何問題?
查看完整描述

2 回答

?
POPMUISE

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()


查看完整回答
反對 回復 2022-09-27
?
波斯汪

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>}


查看完整回答
反對 回復 2022-09-27
  • 2 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號