我有一本字典。“外部”字典是一個時間序列(110 行),每個鍵都是一個日期。在里面我還有另一個字典,其中的鍵是組的名稱。每個日期都有不同數量的組。每個組都是一個資料框,具有固定數量的列(15 個變數),但每個組的行數會發生變化。我只想選擇要提取到 Excel 的 4 個變數。
作業是在 Python 中創建一個 .xlsx 檔案,為檔案命名,遍歷鍵(日期),創建一個新的 Excel 作業表,其中作業表名稱必須是日期(鍵)。然后我想從每個組中提取資料。特定日期的所有組必須在??作業表中作為行列出,然后將 4 個變數作為列列出。
資料示例:
dict_1 = {dict: 110}
'2014-03-01' = {dict: 11}
'2014-04-01' = {dict: 10}
'group_1' = {DataFrame: (4, 15)}
'group_2' = {DataFrame: (2, 15)}
我想象一個像這樣的嵌套回圈:
writer = pd.ExcelWriter('Output.xlsx')
for key in dict_1:
(Here I want to add new sheet and name it based on date/key)
(then loop over groups to extract data to sheet)
我是 Python 新手并使用字典。希望能在正確的方向上得到推動。足以讓我開始。
謝謝!
uj5u.com熱心網友回復:
我使用代碼的注釋進行了解釋。
columns_of_interest = ['col1', 'col2', 'col3', 'col4']
writer = pd.ExcelWriter('Output.xlsx')
for date, subdict in dict_1.items():
# subdict.values() has all the dataframes, we concatenate them
df = pd.concat(list(subdict.values()))
# then we pick our columns
df = df[columns_of_interest]
# and save it as a spread sheet.
df.to_excel(writer, sheet_name=str(date))
writer.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432100.html
