【问题标题】:looping through a dictionary of dataframes in python循环遍历python中的数据框字典
【发布时间】:2019-04-24 13:15:58
【问题描述】:

首先,我写了这个函数:

def writing_in_excel(path, df, sheet_name):
    writer = pd.ExcelWriter(path, datetime_format='m/d/yyyy')
    df.to_excel(writer, sheet_name = sheet_name, index=False, freeze_panes = (0,1))
    writer.save()
    writer.close()

然后,我有一个数据框字典:

import pandas as pd    

employee = {'EmployeeID' : [0,1,2,3,4,5,6,7,8,9],
     'FirstName' : ['a','b','c','d','e','f','g','h','i','j'],
     'LastName' : ['a','b','c','d','e','f','g','h','i','j'],
     'favorite_color' : ['red','blue','green','yellow','red','red','green','blue','green','red']}

df = pd.DataFrame(employee)

by_color_df_dict = dict(tuple(df.groupby('favorite_color')))))

在 'favorite_color' 中,有 4 个不同的值,我想通过 'favorite_color' 中的 4 个值创建单独的数据框

如果您运行该代码,您将获得一个数据帧字典。我想遍历字典并使用上面定义的函数将每个数据帧保存为 excelfile。

我想我必须从:

for key, value in by_color_df_dict:

但我的浅薄知识无法继续。

请帮帮我。

【问题讨论】:

  • 请分享一些示例数据以供使用
  • 我用示例数据编辑了问题
  • 您的预期输出是什么?在问题中添加它
  • 完成 :) 谢谢

标签: python pandas loops dictionary dataframe


【解决方案1】:

你可以这样做

for color_name, group in df.groupby('favorite_color'):
    writing_in_excel('file_name.xlsx', group, color_name)

【讨论】:

  • 我只得到一张带有最后一种颜色的 Excel 表格。我认为这是互相覆盖
  • 也许最好将它们保存在不同的文件中,比如writing_in_excel('{}_file.xlsx'.format(color_name), group, color_name)
  • 或在函数外定义编写器。
  • 知道了。非常感谢
猜你喜欢
  • 2019-08-18
  • 2020-02-14
  • 2015-10-31
  • 2023-03-12
  • 2022-09-22
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多