How to create a data-driven web application in Python?
Python is spreading its wings with each passing day. Data science, data analytics, predictive analysis, descriptive modeling, and associative modeling have become fast, efficient, and effective, thanks to Python frameworks.
Python recently released Streamlit framework. It enables users to build data applications with the least number of lines of code in a few hours. In this blog post, we will follow simple 7 points to build a data-driven web application all in Python. So without further ado, let’s get started…
7 steps to create a Python Web application
- Make sure to have Python installed in your system’s path. To install Streamlit from the command prompt, use a below-mentioned command:
pip install streamlit#https://www.streamlit.io for more information and API documentation
2. Then create a file named AmazonDataApp.py and start writing the code in this Python application file as explained in the next steps.
3. First of all Import Python libraries and give the title of the application as:
#2. importing libraries
import streamlit as st
import pandas as pd
import numpy as np
import itertools as IT
import altair as alt
from PIL import Image
#3. Title of the web application
st.title("Interactive Data Driven Dashboard")
4. After importing libraries, we need to load data in our application, so that we can use this data later. I downloaded the dataset from data.world, to load the data we will write a function:
#4. Load Data function
@st.cache
def load_data(nrows):
data = pd.read_csv('path to data file/amazon-final.csv')
data['date first available'] = pd.to_datetime(data['date first available'])
data = data.sort_values(by=['date first available'])
data = data.set_index(data['date first available'])
data['discount percentage'] = (data['discount percentage'].str.replace("%",'')). astype(int)
lowercase = lambda x: str(x).lower()
data.rename(lowercase, axis='columns', inplace=True)
return data
# Loading data text...
data_load_state = st.text('Loading data...')
# Load 1000 rows of data
data = load_data(1000)
# Successfull data loaded
data_load_state.text("Done! (using st.cache)")
5. Here we will create a toggle button in the form of a checkbox to show data if and when required.
#5. show whole dataset
if st.checkbox('Show raw data'):
st.subheader('Raw data')
st.write(data)
6. Now we will create a DataFrame containing seller and product information, here we are trying to show products corresponding to the sellers. We will do this task with the help of a filter. We will create this filter using multiselect option. This code will do the required task:
#6. show seller and products based on the select filter
sellers = data[['seller name', 'product name']]
options = st.multiselect("Select seller name to show corresponding sold products: ",sellers['seller name'].unique())st.write(options)
show = sellers['seller name'].isin(options)
data_seller = sellers[show]
st.write(data_seller)
7. Finally, we will show mrp, discount %, and sale price in the form of a bar chart. We will show the values with respect to the years. For that, we will create a year filter with the help of a slider widget. The code for this is as under:
#7. Show mrp, discount % and sale price based on the selected year filter in the bar graph
discounts = data[['mrp','discount percentage', 'sale price']]
year_to_filter = st.slider('date', 2014, 2020, 2017) # min: 2015, max: 2020, default: 2017
filtered_data = discounts[data['date first available'].dt.year == year_to_filter]
st.bar_chart(filtered_data)
8. Hence, our data-driven web application is ready to go, to run this application in a web browser, we will type the following code snippet in the command prompt:
streamline run AmazonDataApp.py
After running the above line of code, the application will be available both at the localhost and at the network.
Congratulations! You have created a very simple but interactive web application within a few minutes.
The resultant web application will be like this:
Here is the overall source code:
You can download it from my GitHub gist.
Happy Coding :)