为绘图创建合适的数据框

问题描述 投票:0回答:1

我有以下命令:

dic = {(1, 1, 1): 0.0, (1, 1, 2): 0.0, (1, 1, 3): 1.0, (1, 2, 1): 0.0, (1, 2, 2): 1.0, (1, 2, 3): 0.0, (1, 3, 1): 0.0, (1, 3, 2): 0.0, (1, 3, 3): 0.0, (1, 4, 1): 0.0, (1, 4, 2): 1.0, (1, 4, 3): 0.0, (1, 5, 1): 1.0, (1, 5, 2): 0.0, (1, 5, 3): 0.0, (1, 6, 1): 0.0, (1, 6, 2): 1.0, (1, 6, 3): 0.0, (1, 7, 1): 0.0, (1, 7, 2): 1.0, (1, 7, 3): 0.0, (2, 1, 1): 1.0, (2, 1, 2): 0.0, (2, 1, 3): 0.0, (2, 2, 1): 1.0, (2, 2, 2): 0.0, (2, 2, 3): 0.0, (2, 3, 1): 1.0, (2, 3, 2): 0.0, (2, 3, 3): 0.0, (2, 4, 1): 0.0, (2, 4, 2): 0.0, (2, 4, 3): 0.0, (2, 5, 1): 1.0, (2, 5, 2): 0. 0, (2, 5, 3): 0.0, (2, 6, 1): 0.0, (2, 6, 2): 0.0, (2, 6, 3) 1.0, (2, 7, 1): 0.0, (2, 7, 2): 1.0, (2, 7, 3): 0.0, (3, 1, 1): 1.0, (3, 1, 2): 0.0, (3, 1, 3): 0.0, (3, 2, 1): 0.0, (3, 2, 2): 1.0, (3, 2, 3): 0.0, (3, 3, 1): 0.0, (3, 3, 2): 0.0, (3, 3, 3): 0.0, (3, 4, 1): 1.0, (3, 4, 2): 0.0, (3, 4, 3): 0.0, (3, 5, 1): 1.0, (3, 5, 2): 0.0, (3, 5, 3): 0.0, (3, 6, 1): 1.0, (3, 6, 2): 0.0, (3, 6, 3): 0.0, (3, 7, 1): 0.0, (3, 7, 2): 1.0, (3, 7, 3): 0.0}

想要从中得到一个pandas DataFrame。字典的结构如下。括号中的第一个数字是人物索引 i(应该有这么多行)。第二个数字是标签索引 t。应该有这么多列。第三个数字是正在工作的班次。冒号后的 1 表示该班次已工作,a 表示未工作。如果一天中的所有班次都已过去,且冒号后没有 1,则 0 应代表 i 和 t 的组合,否则该班次有效。根据上面的字典,pandas DataFrame 应该如下所示。

DataFrame:     1  2  3  4  5  6  7 
1              3  2  0  2  1  2  2 
2              1  1  1  0  1  3  2 
3              1  2  0  1  1  3  2 

然后我想用这个功能来使用它。

def visualize(data):
    title_str = f'Title'
    fig = px.imshow(data[[str(i) for i in range(1, 8)]], color_continuous_scale=["red", "orange", "blue", 'black'],
                    title=title_str,)
    fig.update(data=[{'hovertemplate': "Day: %{x}<br>"
                                       "Physician: %{y}<br>",
                      }])
    colorbar = dict(thickness=25,
                     tickvals=[0, 1, 2, 3],
                     ticktext=['Morning', 'Noon', 'Evening', 'Off'])
    fig.update(layout_coloraxis_showscale=True, layout_coloraxis_colorbar=colorbar)
    fig.show()
 
    return fig
pandas dataframe plotly
1个回答
0
投票

如果您的数据集很大,这不会很有效,但它有效:

# get maximum indices for person and tag
max_person = max(key[0] for key in dic.keys())
max_tag = max(key[1] for key in dic.keys())

# initialize empty df
df = pd.DataFrame(index=range(1, max_person + 1), columns=range(1, max_tag + 1))

# populate df using `dic`
for (person, tag, shift), value in dic.items():
    if value == 1.0:
        df.loc[person, tag] = shift

# fill missing values with 0
df = df.fillna(0)
   1  2  3  4  5  6  7
1  3  2  0  2  1  2  2
2  1  1  1  0  1  3  2
3  1  2  0  1  1  1  2
© www.soinside.com 2019 - 2024. All rights reserved.