繁体   English   中英

迭代以生成OrderedDict

[英]Iteration to make OrderedDict

我正在尝试通过迭代制作条形图的有序字典。

在当年的工作代码中,通过这种方式获得条形图的月份:

Jan = pivot_table[1].astype(float).values
Feb = pivot_table[2].astype(float).values
Mar = pivot_table[3].astype(float).values
Apr = pivot_table[4].astype(float).values
May = pivot_table[5].astype(float).values
Jun = pivot_table[6].astype(float).values
Jul = pivot_table[7].astype(float).values
Aug = pivot_table[8].astype(float).values
Sep = pivot_table[9].astype(float).values
Oct = pivot_table[10].astype(float).values
Nov = pivot_table[11].astype(float).values
Dec = pivot_table[12].astype(float).values

然后我将月份写入OrderedDict

months = OrderedDict([('Jan', Jan), ('Feb', Feb), ('Mar', Mar), ('Apr',Apr), ('May',May), ('Jun',Jun),('Jul',Jul), ('Aug',Aug), ('Sep',Sep),('Oct',Oct),('Nov',Nov),('Dec',Dec)])

显然这是不理想的。 因此,我改为编写一个循环。

months=[]
for month in range(1, 13):
    months.append(pivot_table[str(month)].astype(float).values)

months = OrderedDict([('Jan', 1), ('Feb', 2), ('Mar', 3), ('Apr',4), ('May',5), ('Jun',6),('Jul',7), ('Aug',8), ('Sep',9),('Oct',10),('Nov',11),('Dec',12)])

但是,这将返回月份,类型为int,大小为1,值为1,月份为大小为零的列表[]。 不是我想要的!

这是我写条形图的地方:

output_file("stacked_bar.html")
bar = Bar(months, Companies, title="Number of Calls Each Month", palette = palette, legend = "top_right", width = 1200, height=900)
bar.add_tools(hover)


show(bar)

您只是将月份名称映射到数字。 相反,您必须在特定索引处使用months -list的元素。 另请注意,列表中的索引仍然基于零。

months_dict = OrderedDict([('Jan', months[0]), 
                           ('Feb', months[1]), 
                           ..., 
                           ('Dec', months[11])])

您还可以通过使用几个月的列表理解和名称的另一个列表,然后将这些列表压缩在一起,来简化此过程,如下所示:

months = [pivot_table[m].astype(float).values for m in range(1, 13)]
names = ["Jan", "Feb", ..., "Dec"]
months_dict = OrderedDict(list(zip(names, months)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM