Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Streamlit for Data Science
Streamlit for Data Science

Streamlit for Data Science: Create interactive data apps in Python , Second Edition

Arrow left icon
Profile Icon Tyler Richards
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (32 Ratings)
Paperback Sep 2023 300 pages 2nd Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Tyler Richards
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (32 Ratings)
Paperback Sep 2023 300 pages 2nd Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Streamlit for Data Science

Streamlit plotting demo

First, we're going to start to learn how to make Streamlit apps by reproducing the plotting demo we saw before in the Streamlit demo, with a Python file that we've made ourselves. In order to do that, we will do the following:

  1. Make a Python file where we will house all our Streamlit code.
  2. Use the plotting code given in the demo.
  3. Make small edits for practice.
  4. Run our file locally.

Our first step is to create a folder called plotting_app, which will house our first example. The following code makes this folder when run in the terminal, changes our working directory to plotting_app, and creates an empty Python file we'll call plot_demo.py:

mkdir plotting_app
cd plotting_app
touch plot_demo.py

Now that we've made a file called plot_demo.py, open it with any text editor (if you don't have one already, I'm partial to VS Code (https://code.visualstudio.com/download). When you open it up, copy and paste the...

Making an app from scratch

Now that we've tried out the apps others have made, let's make our own! This app is going to focus on using the central limit theorem, which is a fundamental theorem of statistics that says that if we randomly sample with replacement enough from any distribution, then the distribution of the mean of our samples will approximate the normal distribution.

We are not going to prove this with our app, but instead, let's try to generate a few graphs that help explain the power of the central limit theorem. First, let's make sure that we're in the correct directory (in this case, the streamlit_apps folder that we created earlier), make a new folder called clt_app, and toss in a new file.

The following code makes a new folder called clt_app, and again creates an empty Python file, this time called clt_demo.py:

mkdir clt_app
cd clt_app
touch clt_demo.py

Whenever we start a new Streamlit app, we want to make sure to...

Summary

In this chapter, we started by learning how to organize our files and folders for the remainder of this book and quickly moved on to instructions for downloading Streamlit. We then built our first Streamlit application, Hello World, and learned how to run our Streamlit applications locally. Then we started building out a more complicated application to show the implications of the central limit theorem from the ground up, going from a simple histogram to accepting user input and formatting different types of text around our app for clarity and beautification.

By now, you should be comfortable with subjects such as basic data visualization, editing Streamlit apps in a text editor, and locally running Streamlit apps. We're going to dive more deeply into data manipulation in our next chapter.

Exploring Palmer’s Penguins

Before we begin working with this dataset, we should make some visualizations to better understand the data. As we saw before, we have many columns in this data, whether the bill length, the flipper length, the island the penguin lives on, or even the species of penguin. I’ve done the first visualization for us already in Altair, a popular visualization library that we will use extensively throughout this book because it is interactive by default and generally pretty:

Figure 2.2: Bill length and bill depth

From this, we can see that the Adelie penguins have a shorter bill length but generally have fairly deep bills. Now, what does it look like if we plot weight by flipper length?

Figure 2.3: Bill length and weight

Now we see that Gentoo penguins seem to be heavier than the other two species, and that bill length and body mass are positively correlated. These findings are not a huge surprise, but getting to these simple...

Flow control in Streamlit

As we talked about just before, there are two solutions to this data upload default situation. We can provide a default file to use until the user interacts with the application, or we can stop the app until a file is uploaded. Let’s start with the first option. The following code uses the st.file_uploader() function from within an if statement. If the user uploads a file, then the app uses that; if they do not, then we default to the file we have used before:

import altair as alt
import pandas as pd
import seaborn as sns
import streamlit as st
 
st.title("Palmer's Penguins")
st.markdown("Use this Streamlit app to make your own scatterplot about penguins!")
 
penguin_file = st.file_uploader("Select Your Local Penguins CSV (default provided)")
if penguin_file is not None:
    penguins_df = pd.read_csv(penguin_file)
else:
    penguins_df = pd.read_csv("penguins.csv")
 
selected_x_var = st.selectbox(
 ...

Debugging Streamlit apps

We broadly have two options for Streamlit development:

  • Develop in Streamlit and st.write() as a debugger.
  • Explore in Jupyter and then copy to Streamlit.

Developing in Streamlit

In the first option, we write our code directly in Streamlit as we’re experimenting and exploring exactly what our application will do. We’ve basically been taking this option already, which works very well if we have less exploration work and more implementation work to do.

Pros:

  • What you see is what you get – there is no need to maintain both IPython and Python versions of the same app.
  • Better experience for learning how to write production code.

Cons:

  • A slower feedback loop (the entire app must run before feedback).
  • A potentially unfamiliar development environment.

Exploring in Jupyter and then copying to Streamlit

Another option is to utilize the extremely popular Jupyter data science product to write and test out the Streamlit app’s code before placing it in the necessary script and formatting it correctly. This can be useful for exploring new functions that will live in the Streamlit app, but it has serious downsides.

Pros:

  • The lightning-fast feedback loop makes it easier to experiment with very large apps.
  • Users may be more familiar with Jupyter.
  • The full app does not have to be run to get results, as Jupyter can be run in individual cells.

Cons:

  • Jupyter may provide deceptive results if run out of order.
  • “Copying” code over from Jupyter is time-consuming.
  • Python versioning may be different between Jupyter and Streamlit.

My recommendation here is to develop Streamlit apps inside the environment where they are going to be run (that is, a Python file)....

Data manipulation in Streamlit

Streamlit runs our Python file from the top down as a script, so we can perform data manipulation with powerful libraries such as pandas in the same way that we might in a Jupyter notebook or a regular Python script. As we’ve discussed before, we can do all our regular data manipulation as normal. For our Palmer’s Penguins app, what if we wanted the user to be able to filter out penguins based on their gender? The following code filters our DataFrame using pandas:

import streamlit as st
import pandas as pd
import altair as alt 
import seaborn as sns
st.title("Palmer's Penguins")
st.markdown('Use this Streamlit app to make your own scatterplot about penguins!')
penguin_file = st.file_uploader(
    'Select Your Local Penguins CSV (default provided)')
if penguin_file is not None:
    penguins_df = pd.read_csv(penguin_file)
else:
    penguins_df = pd.read_csv('penguins.csv')
selected_x_var =...

An introduction to caching

As we create more computationally intensive Streamlit apps and begin to use and upload larger datasets, we should start thinking about the runtime of these apps and work to increase our efficiency whenever possible. The easiest way to make a Streamlit app more efficient is through caching, which is storing some results in memory so that the app does not repeat the same work whenever possible.

A good analogy for an app’s cache is a human’s short-term memory, where we keep bits of information close at hand that we think might be useful. When something is in our short-term memory, we don’t have to think very hard to get access to that piece of information. In the same way, when we cache a piece of information in Streamlit, we are making a bet that we’ll use that information often.

The way Streamlit caching works more specifically is by storing the results of a function in our app, and if that function is called with the same...

Persistence with Session State

One of the most frustrating parts of the Streamlit operating model for developers starting out is the combination of two facts:

  1. By default, information is not stored across reruns of the app.
  2. On user input, Streamlits are rerun top-to-bottom.

These two facts make it difficult to make certain types of apps! This is best shown in an example. Let’s say that we want to make a to-do app that makes it easy for you to add items to your to-do list. Adding user input in Streamlit is really simple, so we can create one quickly in a new file called session_state_example.py that looks like the following:

import streamlit as st
st.title('My To-Do List Creator')
my_todo_list = ["Buy groceries", "Learn Streamlit", "Learn Python"]
st.write('My current To-Do list is:', my_todo_list)
new_todo = st.text_input("What do you need to do?")
if st.button('Add the new To-Do...

Summary

This chapter was full of fundamental building blocks that we will use often throughout the remainder of this book, and that you will use to develop your own Streamlit applications.

In terms of data, we covered how to bring our own DataFrames into Streamlit and how to accept user input in the form of a data file, which brings us past only being able to simulate data. In terms of other skill sets, we learned how to use our cache to make our data apps faster, how to control the flow of our Streamlit apps, and how to debug our Streamlit apps using st.write(). That’s it for this chapter. Next, we’ll move on to data visualization!

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/sl

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create machine learning apps with random forest, Hugging Face, and GPT-3.5 turbo models
  • Gain an insight into how experts harness Streamlit with in-depth interviews with Streamlit power users
  • Discover the full range of Streamlit’s capabilities via hands-on exercises to effortlessly create and deploy well-designed apps

Description

If you work with data in Python and are looking to create data apps that showcase ML models and make beautiful interactive visualizations, then this is the ideal book for you. Streamlit for Data Science, Second Edition, shows you how to create and deploy data apps quickly, all within Python. This helps you create prototypes in hours instead of days! Written by a prolific Streamlit user and senior data scientist at Snowflake, this fully updated second edition builds on the practical nature of the previous edition with exciting updates, including connecting Streamlit to data warehouses like Snowflake, integrating Hugging Face and OpenAI models into your apps, and connecting and building apps on top of Streamlit databases. Plus, there is a totally updated code repository on GitHub to help you practice your newfound skills. You'll start your journey with the fundamentals of Streamlit and gradually build on this foundation by working with machine learning models and producing high-quality interactive apps. The practical examples of both personal data projects and work-related data-focused web applications will help you get to grips with more challenging topics such as Streamlit Components, beautifying your apps, and quick deployment. By the end of this book, you'll be able to create dynamic web apps in Streamlit quickly and effortlessly.

Who is this book for?

This book is for data scientists and machine learning enthusiasts who want to get started with creating data apps in Streamlit. It is terrific for junior data scientists looking to gain some valuable new skills in a specific and actionable fashion and is also a great resource for senior data scientists looking for a comprehensive overview of the library and how people use it. Prior knowledge of Python programming is a must, and you’ll get the most out of this book if you’ve used Python libraries like Pandas and NumPy in the past.

What you will learn

  • Set up your first development environment and create a basic Streamlit app from scratch
  • Create dynamic visualizations using built-in and imported Python libraries
  • Discover strategies for creating and deploying machine learning models in Streamlit
  • Deploy Streamlit apps with Streamlit Community Cloud, Hugging Face Spaces, and Heroku
  • Integrate Streamlit with Hugging Face, OpenAI, and Snowflake
  • Beautify Streamlit apps using themes and components
  • Implement best practices for prototyping your data science work with Streamlit

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 29, 2023
Length: 300 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803248226
Category :
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 29, 2023
Length: 300 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803248226
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 144.97
Streamlit for Data Science
$54.99
Machine Learning Engineering  with Python
$49.99
Causal Inference and Discovery in Python
$39.99
Total $ 144.97 Stars icon

Table of Contents

14 Chapters
An Introduction to Streamlit Chevron down icon Chevron up icon
Uploading, Downloading, and Manipulating Data Chevron down icon Chevron up icon
Data Visualization Chevron down icon Chevron up icon
Machine Learning and AI with Streamlit Chevron down icon Chevron up icon
Deploying Streamlit with Streamlit Community Cloud Chevron down icon Chevron up icon
Beautifying Streamlit Apps Chevron down icon Chevron up icon
Exploring Streamlit Components Chevron down icon Chevron up icon
Deploying Streamlit Apps with Hugging Face and Heroku Chevron down icon Chevron up icon
Connecting to Databases Chevron down icon Chevron up icon
Improving Job Applications with Streamlit Chevron down icon Chevron up icon
The Data Project – Prototyping Projects in Streamlit Chevron down icon Chevron up icon
Streamlit Power Users Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(32 Ratings)
5 star 78.1%
4 star 12.5%
3 star 0%
2 star 3.1%
1 star 6.3%
Filter icon Filter
Top Reviews

Filter reviews by




N/A Feb 28, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
really accurate, without code sampling problems
Feefo Verified review Feefo
Nikhil Thota Sep 29, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Love it! Tyler's a great author, and breaks down concepts of Streamlit very well 🔥
Amazon Verified review Amazon
Pauline Oct 01, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book for python beginner to learn how to create data apps. Step by step detailed examples/codes to follow along. Easy to understand. Python packages/functions explained or described.
Amazon Verified review Amazon
Amazon Customer Oct 21, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent reference material.Very useful for developing ML models.
Amazon Verified review Amazon
David G Jan 10, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Bought it for my cousins, one is a data engineer and one is swe and both love it. Highly recommend it
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.