python - 嵌套字典在颜色格式方面表现出色

标签 python excel colors

我的字典看起来像这样:

dict1 = { '2020-10-11' : { 
                           'group1':{ 
                                     1 : 2356,
                                     21 : 10001,
                                     34 :  234 
                                   },
                            'group2':{
                                     11 : 999,
                                     2  : 101,
                                     13 : 1234 
                                     } 
                         },
         '2020-10-12' : { 
                           'group1':{ 
                                     11 : 236,
                                     21 : 100,
                                     34 :  34 
                                   },
                            'group2':{
                                     1 : 99,
                                     3 : 121,
                                     2 : 12 
                                     } 
                         }


}

我希望我的输出看起来像这样:

enter image description here

要求是:每个日期的颜色应该不同。

我已经尝试过使用这种方法:

reform = {(level1_key, level2_key, level3_key): values
          for level1_key, level2_dict in dict1.items()
          for level2_key, level3_dict in level2_dict.items()
          for level3_key, values      in level3_dict.items()}

out = pd.DataFrame(reform,index = ['amount']).T
names=['date', 'group', 'id']
out.index.set_names(names, inplace=True)

输出为 xls:

enter image description here

在此之后,我应该如何使用 python 在 excel 中进行颜色格式化?

最佳答案

第一步是完全扁平化结构,以便出现嵌套值的二维表示:

dict1 = {'2020-10-11': {'group1': {1: 2356, 21: 10001, 34: 234}, 'group2': {11: 999, 2: 101, 13: 1234}}, '2020-10-12': {'group1': {11: 236, 21: 100, 34: 34}, 'group2': {1: 99, 3: 121, 2: 12}}}
def flatten(d, c = []):
   flag = True
   for a, b in d.items():
     if isinstance(b, dict):
        yield from flatten(b, c=c+[a] if flag or not c else [*c[:-2],'',a])
     else:
        yield c+[a, b] if flag or not c else [*(['']*(len(c))),a, b]
     flag = False

data = list(flatten(dict1))
#[['2020-10-11', 'group1', 1, 2356], ['', '', 21, 10001], ['', '', 34, 234], ['', 'group2', 11, 999], ['', '', 2, 101], ['', '', 13, 1234], ['2020-10-12', 'group1', 11, 236], ['', '', 21, 100], ['', '', 34, 34], ['', 'group2', 1, 99], ['', '', 3, 121], ['', '', 2, 12]]

接下来,根据结果创建一个 pd.DataFrame 并应用着色:

import pandas as pd
df = pd.DataFrame(data, columns=['Date', 'Group', 'ID', 'Amount'])
writer = pd.ExcelWriter('test_rsults12.xls', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
c_pool = iter([workbook.add_format({'bg_color': '#fff0c1'}), workbook.add_format({'bg_color': '#d5e6f5'})])
fmt = None
for i in range(len(data)):
   if data[i][0]:
      fmt = next(c_pool)
   worksheet.set_row(i+1, cell_format=fmt)

writer.save()

结果:

enter image description here

关于python - 嵌套字典在颜色格式方面表现出色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62774169/

相关文章:

python - Spotify API {'error' : 'invalid_client' } Authorization Code Flow [400]

vba - 尝试在 VBA 中发出 HTTP 请求时出现 "method not valid without suitable object"错误?

excel - 指向 Excel 中相对的其他工作表

java - 如何获取 Activity 时间表的颜色?

python - 使用 "long-data"数据格式合并数据透视表

python - 在 Pandas 中寻找局部最小值

c# - 错误无法评估表达式,因为代码已优化

wpf - Windows8 或 wpf 中的颜色数组?

bash - 如何使存储在变量中的 bash 颜色代码可供外部脚本使用

python - 检查模拟方法的类对象