首页 > 解决方案 > Pandas 将字典转换为字典列表

问题描述

我正在尝试使用 Plotly Gantt 并向视图添加注释,但在添加注释时遇到了问题。我的数据是从标签为 df['Label'] (字符串)的数据框中提取的,但我制作了一个测试数据框“ann”,但在下面没有运气。看起来他们使用的字典列表中间有一个 = 而我的是一个 : - 这是导致问题的原因吗?有什么简单的解决方法吗?我不能像下面那样单独标记所有注释,因为有数百个

正确格式示例:

annots =  [dict(x=LabelDateA,y=0,text="Task label A", showarrow=False, font=dict(color='white')),
           dict(x=LabelDateB,y=1,text="Task label B", showarrow=False, font=dict(color='White')),
           dict(x=LabelDateC,y=2,text="Task label C", showarrow=False, font=dict(color='White'))]
REF: https://stackoverflow.com/questions/56066052/plotly-gantt-chart

错误:

ValueError: 
    Invalid value of type 'builtins.dict_values' received for the 'annotations' property of layout
        Received value: dict_values([{'x': Timestamp('2020-06-01 00:00:00'), 'y': 2, 'text': 'test', 'showarrow': False}, {'x': Timestamp('2020-07-01 00:00:00'), 'y': 5, 'text': 'test3', 'showarrow': False}])

    The 'annotations' property is a tuple of instances of
    Annotation that may be specified as:
      - A list or tuple of instances of plotly.graph_objs.layout.Annotation
      - A list or tuple of dicts of string/value properties that
        will be passed to the Annotation constructor

代码:

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.figure_factory as ff
import plotly.graph_objs as go

# figure
fig = ff.create_gantt(df)

# add annotations
annots =  [dict(x=LabelDateA,y=0,text="Task label A", showarrow=False, font=dict(color='white')),
           dict(x=LabelDateB,y=1,text="Task label B", showarrow=False, font=dict(color='White')),
           dict(x=LabelDateC,y=2,text="Task label C", showarrow=False, font=dict(color='White'))]

print(df)

ann = ann.T.to_dict().values()
print(ann)

# plot figure
fig['layout']['annotations'] = ann
fig.show()

标签: pythonpandasplotly

解决方案


推荐阅读