簡體   English   中英

從 pandas 數據幀制作數據幀字典,而不將其寫入 excel 文件

[英]Making a dictionary of data frames from pandas data frame without writing it to excel file

我有這個正在工作的代碼,但我想修改它,以便在不寫入和讀取 excel 文件的情況下獲得結果。 最后給出預期輸出

 df = pd.DataFrame({'a': ['red', 'yellow', 'red'], 'b': [0.5, 0.25, 0.125],'datetime':[2019-1-1, 2019-5-1, 2019-6-1],})
writer = pd.ExcelWriter('f.xlsx') ### need to modify this to get dfs a dictionary without wriitng to excel
for unique_var in df['a'].unique():
    frame = df[df['a'] == unique_var]
    frame.to_excel(writer, sheet_name=unique_var,index=False)
writer.save()

xl_file = pd.ExcelFile('f.xlsx') 
dfs = {sheet_name: xl_file.parse(sheet_name)  ### dfs is the dictionary of data frames
          for sheet_name in xl_file.sheet_names}

預期 Output

dfs['red']

在此處輸入圖像描述

pandas 有方法.to_dict來做這樣的事情。 您可以執行mydict = pd.to_dict()並將其保存到變量中。 看到這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM