Create a Streamlit application that has a text field to enter a URL (default value: https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv). The app should read the CSV file (and cache it) from the URL and display a DataFrame. Add controls to do the following: - Control how many rows are displayed - A checkbox to determine to randomly shuffle the DataFrame The app should also allow plotting the entire CSV. Users select one or two variables and you must determine the best way to visualize them.
Drop files here
or click to upload
import streamlit as st
import pandas as pd
import altair as alt
# Cache function to read and cache CSV data
def load_data(url):
return pd.read_csv(url)
# Default URL
url = st.text_input('Enter CSV URL', 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv')
# Load Data
@st.cache_data
def get_data():
return load_data(url)
# Load the DataFrame
try:
df = get_data()
except Exception as e:
st.error(f'Error loading CSV: {e}')
df = pd.DataFrame()
# Display DataFrame
if not df.empty:
st.dataframe(df)
# Control for number of rows displayed
row_count = st.slider('Select number of rows to display', 1, min(len(df), 100), 10)
st.write(df.head(row_count))
# Checkbox for shuffling DataFrame
shuffle = st.checkbox('Shuffle DataFrame')
if shuffle:
df = df.sample(frac=1).reset_index(drop=True)
st.write(df.head(row_count))
# Plotting options
x_var = st.selectbox('Select variable for x-axis', df.columns)
y_var = st.selectbox('Select variable for y-axis', df.columns, index=1)
if x_var and y_var:
# Create a scatter plot or line chart depending on variable types
if pd.api.types.is_numeric_dtype(df[x_var]) and pd.api.types.is_numeric_dtype(df[y_var]):
chart = alt.Chart(df).mark_circle(size=60).encode(
x=x_var,
y=y_var,
tooltip=[x_var, y_var]
).interactive()
st.altair_chart(chart, use_container_width=True)
elif pd.api.types.is_numeric_dtype(df[x_var]):
chart = alt.Chart(df).mark_boxplot().encode(
x=x_var,
y=y_var,
tooltip=[x_var, y_var]
).interactive()
st.altair_chart(chart, use_container_width=True)
else:
st.write('Choose appropriate numeric variables for plotting.')
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?