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(
        host='...',
        port=443,
        user="...",
        auth='...',
        http_scheme='https',
        catalog="..."
    )
    sql = '''my query'''
    cursor = conn.cursor()
    cursor.execute(sql)
    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:
        st.session_state.page = 0

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

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

    id = ids[st.session_state.page]
    df_tmp = df[df["id"]==id]
    
    st.dataframe(df_tmp)

get_data_and_show()
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?

Best,
Charly

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:

Charly

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