如何使用pandas和/或plotly在Python中每隔x行创建一个新表?

2024-04-20 04:03:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由熊猫数据框制成的绘图表。我希望每10行创建一个新的Plotly表格,并将该表格另存为图像。有人能帮忙吗?我知道这可能是一个简单的问题,但我对Python还是相当陌生的。以下是我当前的代码示例:

import plotly.graph_objects as go

import pandas as pd

import plotly.io as pio
import os


df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

index = df.index



rowEvenColor = 'white'

rowOddColor = 'lavender'



fig = go.Figure(data=[go.Table(

columnorder = [1,2, 3, 4],

columnwidth = [30,400, 40, 60],

header=dict(values=list(df.columns),

fill_color='navy',

font_color='white',

align=['center', 'left', 'center', 'center']),

cells=dict(values=[df.Rank, df.State, df.Postal, df.Population],

fill_color = [[rowOddColor,rowEvenColor]*len(index)],

font_size=12,

height=60,

align=['center', 'left', 'center', 'left']))

])



fig.update_layout(width=1000, height=600)

fig.show()


if not os.path.exists("images"):

os.mkdir("images")

pio.write_image(fig, 'images/pythont.png', engine="orca")

Tags: importgodfindexosasfigplotly
1条回答
网友
1楼 · 发布于 2024-04-20 04:03:09

您可以在df的每个10行块上循环,创建图形,并为循环的每次迭代保存它。最好还有一个迭代器来跟踪创建了多少个图形,这样每个.png文件都有不同的名称,并且在循环执行时不会被写入

import numpy as np
import pandas as pd

import plotly.graph_objects as go

import plotly.io as pio
import os


df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

# index = df.index

rowEvenColor = 'white'
rowOddColor = 'lavender'
fig_num = 1

for _,df_chunk in df.groupby(np.arange(len(df))//10):
    fig = go.Figure(data=[go.Table(
        columnorder = [1,2, 3, 4],
        columnwidth = [30,400, 40, 60],
        header=dict(values=list(df_chunk.columns),
        fill_color='navy',
        font_color='white',
        align=['center', 'left', 'center', 'center']),
        cells=dict(values=[df_chunk.Rank, df_chunk.State, df_chunk.Postal, df_chunk.Population],
        fill_color = [[rowOddColor,rowEvenColor]*len(df_chunk.index)],
        font_size=12,
        height=60,
        align=['center', 'left', 'center', 'left']))
    ])
    fig.update_layout(width=1000, height=600)
    # fig.show()
    
    if not os.path.exists("images"):
        os.mkdir("images")

    # print("saving fig" + str(fig_num))
    pio.write_image(fig, 'images/fig' + str(fig_num) + '.png', engine="orca")
    fig_num += 1

相关问题 更多 >