Skip to content

Instantly share code, notes, and snippets.

@arita37
Forked from treuille/display_dataframe_quickly.py
Created November 18, 2019 03:59
Show Gist options
  • Save arita37/f2303480b5e902c5bf6c89287031ce6e to your computer and use it in GitHub Desktop.
Save arita37/f2303480b5e902c5bf6c89287031ce6e to your computer and use it in GitHub Desktop.
Workaround: Displaying a dataframe quickly by slicing it.
import streamlit as st
import pandas as pd
import numpy as np
def display_dataframe_quickly(df, max_rows=5000, **st_dataframe_kwargs):
"""Display a subset of a DataFrame or Numpy Array to speed up app renders.
Parameters
----------
df : DataFrame | ndarray
The DataFrame or NumpyArray to render.
max_rows : int
The number of rows to display.
st_dataframe_kwargs : Dict[Any, Any]
Keyword arguments to the st.dataframe method.
"""
n_rows = len(df)
if n_rows <= max_rows:
# As a special case, display small dataframe directly.
st.write(df)
else:
# Slice the DataFrame to display less information.
start_row = st.slider('Start row', 0, n_rows - max_rows)
end_row = start_row + max_rows
df = df[start_row:end_row]
# Reindex Numpy arrays to make them more understadable.
if type(df) == np.ndarray:
df = pd.DataFrame(df)
df.index = range(start_row,end_row)
# Display everything.
st.dataframe(df, **st_dataframe_kwargs)
st.text('Displaying rows %i to %i of %i.' % (start_row, end_row - 1, n_rows))
if __name__ == '__main__':
# An example of using display_dataframe_quickly.
display_dataframe_quickly(st.cache(np.random.randn)(20000, 10), width=400)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment