【问题标题】:Making a dictionary of data frames from pandas data frame without writing it to excel file从熊猫数据框制作数据框字典而不将其写入excel文件
【发布时间】:2021-05-16 10:05:14
【问题描述】:

我有这个工作的代码,但我想修改它,这样我就可以在不写入和读取 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}

预期输出

dfs['red']

【问题讨论】:

  • 是的,你可以,将它们存储在字典中。 dfs = dict(iter(df.groupby("a"))) 现在试试 dfs['red']
  • @anky.can you modify the given code df1 你的意思是df???
  • 已编辑。是的,这就是我的意思。

标签: pandas performance dataframe dictionary runtimemodification


【解决方案1】:

pandas 有 .to_dict 的方法来做这样的事情。您可以执行 mydict = pd.to_dict() 并将其保存到变量中。 见this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2016-12-25
    • 2018-08-01
    • 2016-01-14
    • 2019-01-03
    • 2021-02-15
    相关资源
    最近更新 更多