Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import streamlit as st
- import pandas as pd
- import numpy as np
- #https://towardsdatascience.com/5-python-gui-frameworks-to-create-desktop-web-and-even-mobile-apps-c25f1bcfb561
- # for streamlit(pandas / numpy for everything)
- from dash import Dash, html, dcc
- import plotly.express as px
- import matplotlib.pyplot as plt
- #https://dash.plotly.com/datatable
- #https://towardsdatascience.com/5-python-gui-frameworks-to-create-desktop-web-and-even-mobile-apps-c25f1bcfb561
- #for dash
- from PyQt5 import QtCore, QtGui, QtWidgets
- from PySide6.QtWidgets import QTableView, QApplication
- from PySide6.QtCore import QAbstractTableModel, Qt, QModelIndex
- import sys
- #for PySide6
- import random
- import sys
- from faker import Faker
- #from bootstrap_table import db, User
- from flask_table import Table, Col
- from flask import Flask, request, render_template, session, redirect
- #https://blog.miguelgrinberg.com/post/beautiful-interactive-tables-for-your-flask-templates
- #https://flask-table.readthedocs.io/en/stable/
- #for flask
- #app = Dash(__name__) #running Dash framework without terminal
- app = Flask(__name__)
- def streamlit_ex(): #plot/add buttons/ table(df) / everything else +
- df = pd.read_csv(
- "https://raw.githubusercontent.com/ThuwarakeshM/PracticalML-KMeans-Election/master/voters_demo_sample.csv"
- ) #example of table
- st.title("Interactive K-Means Clustering") #easy to add title
- st.write("Here is the dataset used in this analysis:")
- st.write(df) #display table(or everything)
- arr = np.random.normal(1, 1, size=100) #np array for plot
- fig, ax = plt.subplots()
- ax.hist(arr, bins=20)
- if st.button('Say hello'): #examp of buttons
- st.write('Why hello there')
- else:
- st.write('Goodbye')
- st.pyplot(fig) #examp of plotting
- def Dash_ex(): #good for plot graph, not need to run using terminal +
- #also can be shown the df as table and other datas
- # assume you have a "long-form" data frame
- # see https://plotly.com/python/px-arguments/ for more options
- df = pd.DataFrame({
- "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
- "Amount": [4, 1, 2, 2, 4, 5],
- "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
- })
- fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
- app.layout = html.Div(children=[
- html.H1(children='Hello Dash'),
- html.Div(children='''
- Dash: A web application framework for your data.
- '''),
- dcc.Graph(
- id='example-graph',
- figure=fig
- )
- ])
- class PandasModel(QAbstractTableModel):
- """A model to interface a Qt view with pandas dataframe """
- def __init__(self, dataframe: pd.DataFrame, parent=None):
- QAbstractTableModel.__init__(self, parent)
- self._dataframe = dataframe
- def rowCount(self, parent=QModelIndex()) -> int:
- """ Override method from QAbstractTableModel
- Return row count of the pandas DataFrame
- """
- if parent == QModelIndex():
- return len(self._dataframe)
- return 0
- def columnCount(self, parent=QModelIndex()) -> int:
- """Override method from QAbstractTableModel
- Return column count of the pandas DataFrame
- """
- if parent == QModelIndex():
- return len(self._dataframe.columns)
- return 0
- def data(self, index: QModelIndex, role=Qt.ItemDataRole):
- """Override method from QAbstractTableModel
- Return data cell from the pandas DataFrame
- """
- if not index.isValid():
- return None
- if role == Qt.DisplayRole:
- return str(self._dataframe.iloc[index.row(), index.column()])
- return None
- def headerData(
- self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole
- ):
- """Override method from QAbstractTableModel
- Return dataframe index as vertical header data and columns as horizontal header data.
- """
- if role == Qt.DisplayRole:
- if orientation == Qt.Horizontal:
- return str(self._dataframe.columns[section])
- if orientation == Qt.Vertical:
- return str(self._dataframe.index[section])
- return None
- def Pyside6_ex(): #for pandas df it is not good(need specific class)
- app = QApplication(sys.argv)
- df = pd.read_csv(
- "https://raw.githubusercontent.com/ThuwarakeshM/PracticalML-KMeans-Election/master/voters_demo_sample.csv"
- )
- view = QTableView()
- view.resize(800, 500)
- view.horizontalHeader().setStretchLastSection(True)
- view.setAlternatingRowColors(True)
- view.setSelectionBehavior(QTableView.SelectRows)
- model = PandasModel(df)
- view.setModel(model)
- view.show()
- app.exec()
- class ItemTable(Table):
- name = Col('Name')
- description = Col('Description')
- # Get some objects
- class Item(object):
- def __init__(self, name, description):
- self.name = name
- self.description = description
- @app.route('/', methods=("POST", "GET"))
- def flask_ex():
- items = [Item('Name1', 'Description1'),
- Item('Name2', 'Description2'),
- Item('Name3', 'Description3')]
- # Or, equivalently, some dicts
- items = [dict(name='Name1', description='Description1'),
- dict(name='Name2', description='Description2'),
- dict(name='Name3', description='Description3')]
- # Or, more likely, load items from your database with something like
- #items = ItemModel.query.all()
- # Populate the table
- table = ItemTable(items)
- # Print the html
- return table.__html__()
- # or just {{ table }} from within a Jinja template
- if __name__ == '__main__':
- #Dash_ex() # so-so
- #app.run_server(debug=True)
- #streamlit_ex() #the best variant, but need upgrade to connect not through terminal
- #Pyside6_ex() #not good
- flask_ex()
- # or just {{ table }} from within a Jinja template
- app.run(host='0.0.0.0', port=5000) # Todo add html script for flask
- stop = 0
- #https://www.khanacademy.org/math/statistics-probability/analyzing-categorical-data for test knowledge
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement