Show row by row of a data frame

Hello, I would like to show a data frame block by block using the st.session_state function, I found a solution here (Navigating through dataframe records - #2 by AvratanuBiswas). However, my situation is a bit different in that I need to query to download the data. After following the code in the link above, every time when I click next button, it will run through the whole code to re-download the whole dataset and go to the next row. Is there a way to avoid re-downloading the data? Thank you. @AvratanuBiswas

A simplified version of the code looks like the following:

import streamlit as st
import pandas as pd
import trino

def get_data_and_show():
    conn = trino.dbapi.connect(
    sql = '''my query'''
    cursor = conn.cursor()
    df = pd.DataFrame(cursor.fetchall(), columns=[i[0] for i in cursor.description])
    ids = df["id"].unique()
    n = len(ids)
    if "page" not in st.session_state: = 0

    def next_seqid(): += 1
    def prev_seqid(): -= 1
    if < n-1:
        st.button("Next", on_click=next_seqid) 

    if > 0:
        st.button("Previous", on_click=prev_seqid) 

    id = ids[]
    df_tmp = df[df["id"]==id]

1 Like

Hi @heming611, and welcome to our forums! :wave:

I think the problem in the provided code is that every time your app reruns (e.g., due to a button press), it fetches the data from the database. To avoid fetching data from the db every time, did you try to use Streamlit’s st.cache_data() function?


Thank you so much, @Charly_Wargnier, that is what I am looking for. It worked out perfectly (I used st.cache_data instead since st.cache is deprecated)

Glad it worked, and yes, I was meant to say st.cache_data()! :wink:

(I amended my above answer accordingly)

Happy Streamlit’ing! :balloon:


This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.