Q: How to create new table in Python every x rows using pandas and/or plotly? I have a Plotly table made from a pandas data frame. I want to create a new Plotly table every 10 rows and save that table as an image. Can anyone help? I know this is probably a simple question, but I'm pretty new to Python. Here is my current code as an example:
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")


A: You can loop over each 10 row chunk of your df, create your figure, and save it for each iteration of the loop. It might be good to also have some an iterator to keep track of how many figures are created, so that each .png file has a different name and isn't written over as the loop executes.
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

