【问题标题】:Automatically generate required Plotly data structure自动生成所需的 Plotly 数据结构
【发布时间】:2019-06-05 08:27:52
【问题描述】:

我想使用 Plotly 在 Python3 中生成交互式散点图。 Plotly 要求数据的输入采用特定格式。我希望能够自动生成格式,因为我有很多数据。

Plotly 需要以下格式的散点图数据

fig = {
    'data': [
  {
        'x': sim_corr.AAK1, 
        'y': sim_pas.AAK1, 
        'text': sim_corr.index, 
        'mode': 'markers', 
        'name': 'AAK1'},
        {
        'x': sim_corr.ABL1, 
        'y': sim_pas.ABL1, 
        'text': sim_corr.index, 
        'mode': 'markers', 
        'name': 'ABL1'},
            {
        'x': sim_corr.ABL2, 
        'y': sim_pas.ABL2, 
        'text': sim_corr.index, 
        'mode': 'markers', 
        'name': 'ABL2'}
],
    'layout': {
        'title':'Correlation VS PAS',
        'hovermode':'closest',
        'xaxis': {'title': 'Correlations'},
        'yaxis': {'title': "PAS"}
    }
}

其中 sim_corr 和 sim_pas 是两个 pandas 数据帧,AAK1 是两个数据帧中的列名。上面只有 207 列中的 3 列。我通过手动输入每一列来生成绘图,但我确信有更有效的方法。我真的不知道这将如何完成。

这是在较小规模上生成类似数据帧的代码,

import pandas as pd
df1 = pd.DataFrame(data = [[1,2,3,4], [4,5,6,7], [7,8,9,10], [10,11,12,13]], index = ["a", 'b', 'c', 'd'], columns = ['col1', 'col2', 'col3', 'col4'])
df2 = pd.DataFrame(data = [[4,2,5,4], [1,5,3,7], [2,8,5,10], [3,11,7,13]], index = ["a", 'b', 'c', 'd'], columns = ['col1', 'col2', 'col3', 'col4'])


预期的结果是自动为两个共享相同列名的数据框中的所有列生成所需结构的数据输入。

【问题讨论】:

    标签: python-3.x plotly


    【解决方案1】:

    好的,所以我找到了一种创建此图的方法,比手动输入数据要快得多。首先在您的第一个数据框中创建一个列名列表。使用上面提供的示例代码:

    g = []
    for i in range(0,len(df1.columns)):
        x = str("df1." + df1.columns[i])
        g.append(x)
    

    第二个创建第二个数据框中的列名列表。

    h = []
    for i in range(0,len(df2.columns)):
        x = str("df2." + df2.columns[i])
        h.append(x)
    

    最后在遍历步骤 1 和 2 中创建的两个列表中的列名时创建一个字典列表:

    dics = []
    for i in range(0,len(df1.columns)):
        d = {'x': g[i],
             'y': h[i],
             'text':df1.index,
             'mode':'markers',
             'name':str(df1.columns[i])}
        dics.append(d)
    

    现在 dics 包含所需格式的数据输入。如果有人知道更有效的方法,请在下面添加。

    【讨论】:

    • 这是目前要走的路。我正在为我正在构建的每个更大的项目做这个。 :) 对于大数据集仍然非常低效。
    猜你喜欢
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    相关资源
    最近更新 更多