Wednesday, 22 October 2025

#19 Web site Demo

Python Website Demo: Full Tutorial (Login, Projects, Customers, Stories)

Python Website Demo Tutorial

Build a complete demo web application using Python + Flask, featuring: login, projects, customers, and success stories pages. Each module gets you closer to a real-world site!

Module 1: Setup & Install Flask

pip install flask flask-login
mkdir pywebdemo
cd pywebdemo
touch app.py
mkdir templates static

Module 2: Base Flask App & Page Routing

# app.py
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/projects')
def projects():
    return render_template('projects.html')

@app.route('/customers')
def customers():
    return render_template('customers.html')

@app.route('/stories')
def stories():
    return render_template('stories.html')

if __name__ == '__main__':
    app.run(debug=True)

Module 3: Basic Page Templates

<!-- templates/home.html -->
<h1>Welcome to Demo Company</h1>
<a href="/login">Login</a> | <a href="/projects">Projects</a> | <a href="/customers">Customers</a> | <a href="/stories">Success Stories</a>
<!-- templates/projects.html -->
<h2>Our Projects</h2>
<ul>
  <li>Project A: AI Web Platform</li>
  <li>Project B: Mobile Solution</li>
</ul>
<!-- templates/customers.html -->
<h2>Our Customers</h2>
<ul>
  <li>Customer Alpha</li>
  <li>Customer Beta</li>
</ul>
<!-- templates/stories.html -->
<h2>Success Stories</h2>
<p>Customer Alpha tripled sales with our platform!</p>
<p>Customer Beta expanded globally with our mobile tech.</p>

Module 4: Login Page & User System

# app.py (add)
from flask import request, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app.secret_key = 'REPLACE_WITH_A_SECRET_KEY'
login_manager = LoginManager()
login_manager.init_app(app)

# Simple Fake User
class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)
# app.py (add route)
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['username'] == 'admin' and request.form['password'] == 'password':
            user = User('admin')
            login_user(user)
            return redirect(url_for('home'))
        else:
            flash('Bad credentials!')
    return render_template('login.html')
<!-- templates/login.html -->
<form method="POST">
  <label>Username:</label>
  <input name="username" type="text"><br>
  <label>Password:</label>
  <input name="password" type="password"><br>
  <button type="submit">Login</button>
</form>
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <p style="color:red;">{{ messages[0] }}</p>
  {% endif %}
{% endwith %}
# app.py (add route)
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('home'))

Module 5: Protected Pages and Navigation

# app.py (protect routes)
@app.route('/admin')
@login_required
def admin():
    return "

Admin Only Page

"

Module 6: Basic Styling and Navigation Bar

<!-- templates/base.html -->
<nav>
  <a href="/">Home</a> | 
  <a href="/projects">Projects</a> | 
  <a href="/customers">Customers</a> | 
  <a href="/stories">Success Stories</a> | 
  {% if current_user.is_authenticated %}
    <a href="/logout">Logout</a>
  {% else %}
    <a href="/login">Login</a>
  {% endif %}
</nav>
<hr>
{% block content %}{% endblock %}
<!-- Usage: in your pages -->
{% extends "base.html" %}
{% block content %}
  ...page content...
{% endblock %}
/* static/style.css */
body { font-family: Arial, sans-serif; background: #f7faff; }
nav { font-size: 1.2em; margin-bottom: 12px; }
a { color: #00adb5; text-decoration: none; margin-right: 10px; }
hr { margin-bottom: 30px; }

Module 7: Adding Fake Data for Projects & Customers

# app.py
projects_data = [
  {"title": "AI Web Platform", "desc": "Cutting-edge machine learning project."},
  {"title": "Mobile Solution", "desc": "Cross-platform mobile app."}
]
customers_data = ["Customer Alpha", "Customer Beta"]

@app.route('/projects')
def projects():
    return render_template('projects.html', projects=projects_data)

@app.route('/customers')
def customers():
    return render_template('customers.html', customers=customers_data)
{% extends "base.html" %}
{% block content %}
  <h2>Our Projects</h2>
  <ul>
    {% for p in projects %}
      <li><b>{{ p.title }}</b> — {{ p.desc }}</li>
    {% endfor %}
  </ul>
{% endblock %}

Module 8: Success Stories Dynamic Content

# app.py
stories_data = [
  {"customer": "Alpha", "story": "Tripled sales!"},
  {"customer": "Beta", "story": "Expanded globally!"}
]

@app.route('/stories')
def stories():
    return render_template('stories.html', stories=stories_data)
{% extends "base.html" %}
{% block content %}
  <h2>Success Stories</h2>
  <ul>
    {% for s in stories %}
      <li><b>{{ s.customer }}:</b> {{ s.story }}</li>
    {% endfor %}
  </ul>
{% endblock %}

Module 9: Flash Messages & User Feedback

# On login fail (see login above)
flash('Bad credentials!')
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <div style="color:red;">
    {% for message in messages %}
      {{ message }}<br>
    {% endfor %}
    </div>
  {% endif %}
{% endwith %}

Module 10: Finalizing & Running Your Demo Website

export FLASK_APP=app.py
flask run
  1. Visit http://127.0.0.1:5000/ in your browser.
  2. Login using admin / password (demo only).
  3. Explore projects, customers, and stories pages.
  4. You can expand with databases, forms, and REST APIs later!
This boilerplate gives you a fast way to try out and demo a real Python-based web application!

#18 gmail AUthentication

Gmail Authentication with Django: Step-by-Step Tutorial

Gmail Authentication in Django: Step-by-Step Tutorial

Learn how to set up Gmail (Google) authentication on your Django site using the popular third-party package django-allauth. This method lets users log in or sign up with their Google account in a secure, scalable way.

Step 1: Install Required Packages

pip install django-allauth

Step 2: Add Apps and Settings in settings.py

INSTALLED_APPS = [
    # Django default apps...
    "django.contrib.sites",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
]

SITE_ID = 1

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

LOGIN_REDIRECT_URL = "/"

Step 3: Add Allauth URLs to Project

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
]

Step 4: Create a Google OAuth App

  • Go to Google Cloud Console > APIs & Services > Credentials
  • Create a new OAuth Client ID (Web application)
  • Add authorized redirect URI: http://localhost:8000/accounts/google/login/callback/
  • Save your Client ID and Secret.

Step 5: Configure Google Provider in Django Admin

  1. Run the server and log in to /admin
  2. Find Sites and make sure domain is localhost
  3. Find Social applications and add Google:
    • Provider: Google
    • Name: Google
    • Client ID: (your Google client ID)
    • Secret Key: (your Google secret)
    • Sites: Select your current site

Step 6: Customizing Login Button in Template

<a href="{% provider_login_url 'google' %}">
  Login with Google
</a>

Step 7: Try It Out!

  • Visit /accounts/login/ and click Login with Google
  • Authenticate with your Gmail account
  • Get redirected to your app, now signed in!

Extra: Customizing Forms, User Model, and Redirects

  • Override templates in templates/account/
  • Extend user model for extra fields if needed
  • Change LOGIN_REDIRECT_URL for custom flows
With django-allauth, you can add many other social providers easily (Facebook, Twitter, etc).

#17 Django

Django Masterclass: 10 Modules to Professional Web Apps

Django Masterclass: 10 Modules to Professional Web Apps

Step up to building robust, scalable web applications with Django! This 10-part blog series takes you from setup to production deployment through hands-on modules with code, explanations, and best practices.

Module 1: Introduction to Django & Installation

pip install django
django-admin startproject mysite
cd mysite
python manage.py runserver

Module 2: Django App Structure Explained

python manage.py startapp blog
  • mysite/ (project root)
  • blog/ (your app: models, views, templates)
  • manage.py (Django CLI)

Module 3: Models and Admin

# blog/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Module 4: Views and URLs

# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all()
    return render(request, "post_list.html", {"posts": posts})
# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.post_list, name="post_list"),
]
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("blog.urls")),
]

Module 5: Templates and Static Files

{% for post in posts %}
  <h2>{{ post.title }}</h2>
  <p>{{ post.body }}</p>
  <small>{{ post.pub_date }}</small>
{% endfor %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
python manage.py collectstatic

Module 6: Forms and User Input

# blog/forms.py
from django import forms

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "body"]
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Publish</button>
</form>

Module 7: Authentication (Login, Logout, Signup)

from django.contrib.auth import login, logout, authenticate
# Use Django's built-in auth views, templates, and User model for user management.
# mysite/urls.py (add)
from django.contrib.auth import views as auth_views
urlpatterns += [
    path("login/", auth_views.LoginView.as_view(), name="login"),
    path("logout/", auth_views.LogoutView.as_view(), name="logout"),
]
<a href="{% url 'login' %}">Log In</a>
<a href="{% url 'logout' %}">Log Out</a>

Module 8: Advanced Features – Class-based Views & Pagination

from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    paginate_by = 5
    template_name = "post_list.html"
# blog/urls.py (add)
path("posts/", PostListView.as_view(), name="post_list"),

Module 9: REST API with Django Rest Framework

pip install djangorestframework
# blog/api.py
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
# blog/serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = "__all__"
# mysite/urls.py (add)
from rest_framework import routers
from blog.api import PostViewSet

router = routers.DefaultRouter()
router.register(r"posts", PostViewSet)
urlpatterns += [
    path("api/", include(router.urls)),
]

Module 10: Deployment to Production

  1. Create requirements.txt:
    pip freeze > requirements.txt
    
  2. Push to GitHub
    git init
    git add .
    git commit -m "Deploy Django app"
    git remote add origin https://github.com/yourname/yourrepo.git
    git push -u origin master
    
  3. Deploy on Render, Heroku, or any cloud provider:
    web: gunicorn mysite.wsgi
    
  4. Collect static files on server:
    python manage.py collectstatic
    
Django supports secure admin, scalable apps, and RESTful APIs with best practices and rapid development.

#16 FAST API

FastAPI Masterclass: 10 Modules

FastAPI Masterclass: Build & Deploy APIs in 10 Modules

This comprehensive guide introduces you to FastAPI, the modern Python framework for building high-performance APIs and web apps. Each module builds on the next, taking you from setup to deployment.

Module 1: Introduction to FastAPI

FastAPI is a high-performance web framework built for speed with async support. Install it and run your first app.

pip install fastapi uvicorn
# app.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello FastAPI"}

# Run with: uvicorn app:app --reload

Module 2: Path and Query Parameters

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "query": q}

Module 3: Request Body with Pydantic

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None

@app.post("/items/")
def create_item(item: Item):
    return {"item": item}

Module 4: Handling Responses

Customize your JSON responses and status codes.

from fastapi.responses import JSONResponse

@app.get("/custom")
def custom_response():
    return JSONResponse(content={"status": "success"}, status_code=201)

Module 5: Error Handling

from fastapi import HTTPException

@app.get("/divide")
def divide(a: int, b: int):
    if b == 0:
        raise HTTPException(status_code=400, detail="Division by zero not allowed")
    return {"result": a / b}

Module 6: Background Tasks

from fastapi import BackgroundTasks

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(f"{message}\n")

@app.post("/log/")
def log_message(background_tasks: BackgroundTasks, message: str):
    background_tasks.add_task(write_log, message)
    return {"status": "Task scheduled"}

Module 7: Working with Databases (SQLite + SQLAlchemy)

pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

Base.metadata.create_all(bind=engine)

Module 8: Authentication with FastAPI

from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_current_user(token: str = Depends(oauth2_scheme)):
    return {"token": token}

Module 9: Building a RESTful API

users = []

@app.post("/users/")
def create_user(name: str):
    user = {"id": len(users) + 1, "name": name}
    users.append(user)
    return user

@app.get("/users/")
def get_users():
    return users

Module 10: Deploying FastAPI (Using Uvicorn + Git)

  1. Create a requirements.txt file:
    pip freeze > requirements.txt
    
  2. Create a Procfile for Heroku/Render:
    web: uvicorn app:app --host=0.0.0.0 --port=$PORT
    
  3. Push to GitHub and Deploy via Render or Heroku Dashboard.
FastAPI automatically generates interactive API docs at /docs and /redoc!

#15 Locate your phone number

Flask: Locate Phone Numbers by Region & Carrier

Build a Flask App to Locate Phone Numbers

This guide shows you how to create a Python Flask web tool that locates phone numbers—revealing region and carrier information using the phonenumbers library.

Step 1: Install Requirements

pip install Flask phonenumbers

Step 2: Create the Flask App (app.py)

from flask import Flask, request, render_template_string
import phonenumbers
from phonenumbers import geocoder, carrier

app = Flask(__name__)

TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>Phone Number Locator</title>
    <style>
        body { font-family: Arial, sans-serif; margin:40px; }
        .container { max-width: 500px; margin: auto; }
        input[type=text] { width: 80%; padding: 8px; }
        input[type=submit] { padding: 8px 16px; }
        .result { margin-top:20px; background: #f0fafc; padding: 16px; border-radius: 5px;}
    </style>
</head>
<body>
    <div class="container">
        <h2>Phone Number Locator</h2>
        <form method="post">
            <label for="phone">Enter Phone Number (with country code):</label><br><br>
            <input type="text" name="phone" placeholder="+14155552671"/><br><br>
            <input type="submit" value="Locate">
        </form>
        {% if info %}
        <div class="result">
            <b>Number:</b> {{ info['number'] }} <br>
            <b>Country/Region:</b> {{ info['region'] }} <br>
            <b>Carrier:</b> {{ info['carrier'] }} <br>
        </div>
        {% endif %}
    </div>
</body>
</html>
"""

@app.route('/', methods=['GET', 'POST'])
def locate():
    info = None
    if request.method == 'POST':
        number = request.form['phone']
        try:
            parsed = phonenumbers.parse(number, None)
            region = geocoder.description_for_number(parsed, "en")
            carrier_name = carrier.name_for_number(parsed, "en")
            info = {
                'number': number,
                'region': region if region else 'Unknown',
                'carrier': carrier_name if carrier_name else 'Unknown'
            }
        except Exception as e:
            info = {'number': number, 'region': 'Invalid number', 'carrier': 'Invalid number'}
    return render_template_string(TEMPLATE, info=info)

if __name__ == '__main__':
    app.run(debug=True)

Step 3: Run Locally

python app.py
Open http://127.0.0.1:5000/ in your browser.
Enter an international phone number (e.g., +14155552671 for US).

Features

  • Input any phone number in international format
  • Returns region/country and carrier name
  • Simple, clean HTML interface
  • Shows error for invalid phone numbers

#14 Develop and Deploy Flask

Flask: Build & Deploy Fast—From Local App to Git Hosting

Flask: Build & Deploy Fast

This guide walks you through developing a simple Flask app and deploying it to production using Git and a web dashboard such as Render or Heroku.

Step 1: Set Up Your Flask App Locally

  1. Install Flask:
    pip install flask
  2. Create app.py:
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return "Hello, Flask World!"
    
    if __name__ == '__main__':
        app.run(debug=True)
    
  3. Test your app locally:
    python app.py
    Open http://127.0.0.1:5000/ in your browser. You should see “Hello, Flask World!”

Step 2: Prepare for Deployment

  1. Create a requirements.txt file:
    pip freeze > requirements.txt
  2. Add a Procfile (for platforms like Heroku or Render):
    web: gunicorn app:app
  3. Install Gunicorn (for production server):
    pip install gunicorn

Step 3: Push Your Code to GitHub

  1. Initialize and push to a new Git repo:
    git init
    git add .
    git commit -m "Initial Flask app"
    git remote add origin https://github.com/yourusername/your-repo.git
    git push -u origin master
    

Step 4: Deploy Using a Web Dashboard (Heroku/Render)

  1. On Render or Heroku:
    • Create a new Web Service or App
    • Connect your GitHub repository
    • Build command: pip install -r requirements.txt
    • Start command: gunicorn app:app
    • Click Deploy!
  2. Visit your live app URL:
    You’ll receive a unique URL (e.g., https://your-app.onrender.com) to access your Flask app in production.

Summary

  • Develop Flask locally, test, and verify
  • Prepare deployment files needed for cloud hosting
  • Push code to GitHub
  • Deploy from a browser-friendly dashboard—no CLI required!
  • Share your app with the world!

#13 Deploying to github using browser

Deploying Flask via Git & Web Dashboard

  1. 1. Push your code to GitHub:
    git init
    git add .
    git commit -m "Initial commit"
    git remote add origin https://github.com/yourusername/your-repo.git
    git push -u origin master
    
  2. 2. Create a requirements.txt file:
    pip freeze > requirements.txt
    
  3. 3. Create a Procfile (for Heroku/Render):
    web: gunicorn app:app
    
  4. 4. Log in to Render/Heroku Web Dashboard:
    • Create a new "Web Service" or "App"
    • Connect your GitHub repository
    • Set the build and start commands (Render: pip install -r requirements.txt, start: gunicorn app:app)
    • Deploy!
  5. 5. View your live Flask app at the provided URL.

#12 Flask fundas

Python Flask Masterclass: 10 Modules

Python Flask Masterclass: Learn by Building

This tutorial introduces Flask fundamentals through 10 progressively complex modules—from setup to deployment.

Module 1: Introduction to Flask

Flask is a lightweight WSGI web framework for Python. Let’s start by installing and running a simple app.

pip install Flask
# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"
    
if __name__ == '__main__':
    app.run(debug=True)

Module 2: Routing and URL Parameters

Explore dynamic URL routes and parameter passing.

from flask import Flask
app = Flask(__name__)

@app.route('/user/<username>')
def show_user(username):
    return f"Welcome {username}!"

Module 3: Templates with Jinja2

Use Flask with HTML templates stored in a templates/ folder.

from flask import render_template

@app.route('/greet/<name>')
def greet(name):
    return render_template('greet.html', name=name)
<!DOCTYPE html>
<html>
  <body>
    <h2>Hello, {{ name }}!</h2>
  </body>
</html>

Module 4: Static Files (CSS & JS)

Serve CSS and JS from a static/ folder.

@app.route('/profile')
def profile():
    return render_template('profile.html')
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<h1>My Profile</h1>

Module 5: Request Handling and Forms

Learn to use GET and POST methods.

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = request.form['username']
        return f"Welcome {user}"
    return '''
    <form method="post">
        <input name="username">
        <input type="submit">
    </form>'''

Module 6: Flask Blueprints (Modular Apps)

Organize large apps using Blueprints.

# blog/routes.py
from flask import Blueprint

blog = Blueprint('blog', __name__)

@blog.route('/posts')
def posts():
    return "Blog posts list"
# main.py
from flask import Flask
from blog.routes import blog

app = Flask(__name__)
app.register_blueprint(blog)

Module 7: Working with Databases (SQLite + SQLAlchemy)

Integrate Flask with SQLAlchemy ORM.

pip install flask_sqlalchemy
from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

Module 8: REST APIs with Flask

Build APIs using Flask and jsonify.

from flask import jsonify

@app.route('/api/data')
def get_data():
    data = {'message': 'Hello API'}
    return jsonify(data)

Module 9: Authentication (Flask-Login)

Handle user sessions and login management.

pip install flask-login
from flask_login import LoginManager, UserMixin, login_user

login_manager = LoginManager(app)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)

Module 10: Deployment on Render or Heroku

Production setup with gunicorn and requirements.txt.

pip install gunicorn
web: gunicorn app:app

Deploy using Git or Render web dashboard.

Tuesday, 21 October 2025

#2.2 ๐Ÿงฎ Numpy Cook Book

NumPy Concepts with Demos

This blog covers essential NumPy concepts with simple code examples. Each demo has syntax highlighting and a copy button — perfect for learning or sharing!


1. Importing NumPy

import numpy as np

2. Creating Arrays

# From list
a = np.array([1, 2, 3])
print(a)

# From tuple
b = np.array((4, 5, 6))
print(b)

3. Array Dimensions

a = np.array([[1, 2], [3, 4]])
print(a.ndim)   # 2
print(a.shape)  # (2,2)
print(a.size)   # 4

4. Array Data Types

a = np.array([1, 2, 3], dtype=np.float64)
print(a.dtype)

5. Array Indexing

a = np.array([10, 20, 30, 40, 50])
print(a[1])   # 20
print(a[-1])  # 50

6. Slicing Arrays

print(a[1:4])  # [20 30 40]
print(a[:3])   # [10 20 30]
print(a[::2])  # [10 30 50]

7. Array Operations

b = np.array([4, 5, 6])
print(a + b)        # [14 25 36]
print(a * b)        # [40 100 180]
print(np.dot(a, b)) # Dot product

8. Universal Functions (ufuncs)

a = np.array([1, 4, 9])
print(np.sqrt(a))  # [1. 2. 3.]
print(np.exp(a))   # e^a

9. Reshaping Arrays

a = np.array([1, 2, 3, 4, 5, 6])
b = a.reshape((2, 3))
print(b)

10. Stacking Arrays

a = np.array([1, 2])
b = np.array([3, 4])
c = np.vstack((a, b))
print(c)

11. Splitting Arrays

a = np.array([1, 2, 3, 4, 5, 6])
b, c = np.hsplit(a, 2)
print(b)
print(c)

12. Random Numbers

a = np.random.rand(3, 2)
print(a)

13. Array Broadcasting

a = np.array([1, 2, 3])
b = np.array([1])
print(a + b)  # [2 3 4]

14. Saving and Loading Arrays

a = np.array([1, 2, 3])
np.save('my_array.npy', a)
b = np.load('my_array.npy')
print(b)

# 2.1 Pandas - Cook Book

Pandas Concepts with Demos

๐Ÿผ Pandas Concepts with Demo Programs

This blog covers essential Pandas concepts with simple code examples. Each demo has syntax highlighting and a copy button — perfect for learning or sharing!


1. Importing Pandas & NumPy

import pandas as pd
import numpy as np

2. Creating Series & DataFrames

# Series
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)

# DataFrame from NumPy array
dates = pd.date_range("20230101", periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list("ABCD"))
print(df)

# DataFrame from dictionary
df2 = pd.DataFrame({
    "A": 1.0,
    "B": pd.Timestamp("20230102"),
    "C": pd.Series(1, index=list(range(4)), dtype="float32"),
    "D": np.array([3]*4, dtype="int32"),
    "E": pd.Categorical(["test", "train", "test", "train"]),
    "F": "foo",
})
print(df2)
print(df2.dtypes)

3. Viewing Data

print(df.head())  # Top 5 rows
print(df.tail(3))  # Last 3 rows

4. Selecting Columns

print(df["A"])       # Single column
print(df[["A", "B"]]) # Multiple columns

5. Selecting Rows

print(df.loc[dates[0]])        # Row by label
print(df.iloc[0:3, 0:2])       # Row and column by integer position

6. Boolean Indexing

print(df[df["A"] > 0])  # Rows where column A > 0
print(df[df > 0])         # All positive values

7. Setting Values

df.iloc[0, 1] = 100
df.loc[:, "B"] = np.array([1]*6)
print(df)

8. Handling Missing Data

df2 = df.copy()
df2.iloc[0, 0] = np.nan
print(df2.dropna())  # Drop rows with NaN
print(df2.fillna(0)) # Fill NaN with 0

9. Operations & Descriptive Statistics

print(df.mean())      # Column-wise mean
print(df.cumsum())    # Cumulative sum
print(df.describe())  # Summary statistics

10. Apply & Map

df2 = df.apply(np.cumsum)
print(df2)

df["A"] = df["A"].map(lambda x: x*2)
print(df)

11. Sorting

df.sort_index(axis=1, ascending=False, inplace=True)  # Sort columns
df.sort_values(by="B", ascending=True, inplace=True)    # Sort rows by column B
print(df)

12. Merging & Concatenating

df1 = pd.DataFrame(np.random.randn(3, 4), columns=list("ABCD"))
df2 = pd.DataFrame(np.random.randn(3, 4), columns=list("ABCD"))
result = pd.concat([df1, df2])
print(result)

13. Grouping

df = pd.DataFrame({
    "A": ["foo", "bar", "foo", "bar"],
    "B": ["one", "one", "two", "two"],
    "C": np.random.randn(4),
    "D": np.random.randn(4)
})
grouped = df.groupby("A").sum()
print(grouped)

#10 ๐Ÿค–Streamlit + LangChain — Build Agentic AI Dashboards

Combine the power of Streamlit (for RIA's [Rich Internet Application]  in pure Python) and LangChain (for agentic workflows, tools, memory, chains) to build sleek AI dashboards that think, act, and respond. Whether you’re creating a chat-agent, document assistant, or data-query bot — this guide gets you started fast. ๐Ÿš€


1️⃣ Install the Libraries


!pip install streamlit langchain openai tiktoken

2️⃣ Build a Simple Agent Dashboard


import streamlit as st
from langchain.llms import OpenAI
from langchain import LLMChain
from langchain.prompts import PromptTemplate

st.set_page_config(page_title="Agentic AI Dashboard", layout="wide")
st.title("๐Ÿค– Ask Me Anything: AI Agent")

openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")

if openai_api_key:
    prompt = PromptTemplate(
        input_variables=["question"],
        template="You are a helpful assistant. Answer: {question}"
    )
    llm = OpenAI(openai_api_key=openai_api_key, temperature=0.5)
    chain = LLMChain(llm=llm, prompt=prompt)

    user_question = st.text_area("Enter your question:")
    if st.button("Ask"):
        response = chain.run(user_question)
        st.info(response)
else:
    st.warning("Please enter your OpenAI API Key in the sidebar.")

3️⃣ Add Tools and Agent with Thought Trace

Use LangChain Agent with tools and display agent thoughts/actions.


import streamlit as st
from langchain.agents import initialize_agent, Tool, AgentType
from langchain.llms import OpenAI
from langchain_community.callbacks.streamlit import StreamlitCallbackHandler

st.title("๐Ÿ› ️ Agent with Tools Demo")
openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")

if openai_api_key:
    llm = OpenAI(openai_api_key=openai_api_key, streaming=True)
    tools = [
        Tool(name="calculator", func=lambda x: eval(x), description="Evaluate math expressions")
    ]
    agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

    query = st.text_area("Ask the agent (it may use tools):")
    if st.button("Submit"):
        with st.container():
            callback = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
            result = agent.run(query, callbacks=[callback])
            st.success(result)
else:
    st.warning("Enter OpenAI API Key in sidebar.")

4️⃣ Document Upload + Q&A Dashboard


import streamlit as st
import pandas as pd
from langchain.chat_models import ChatOpenAI
from langchain.agents import create_pandas_dataframe_agent
from langchain.agents.agent_types import AgentType

st.title("๐Ÿ“„ Ask Your Data Dashboard")
uploaded_file = st.file_uploader("Upload CSV", type=["csv"])
openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")

if uploaded_file and openai_api_key:
    df = pd.read_csv(uploaded_file)
    st.dataframe(df.head())

    agent = create_pandas_dataframe_agent(
        llm=ChatOpenAI(openai_api_key=openai_api_key),
        df=df,
        agent_type=AgentType.OPENAI_FUNCTIONS,
        verbose=True
    )

    user_query = st.text_input("What do you want to ask about the data?")
    if st.button("Run Query"):
        response = agent.run(user_query)
        st.info(response)
else:
    st.warning("Please upload a CSV and enter OpenAI API Key.")

5️⃣ Deployment Tips

Once your dashboard works locally, deploy it via Streamlit Community Cloud — simply push your code + `requirements.txt` and click “Deploy”. Use `st.secrets.toml` to securely manage your OpenAI API key.


✅ What You Can Build Next

  • ๐Ÿง  Chatbots with memory, custom tools & chain logic
  • ๐Ÿ“Š Data-agents that ingest documents, spreadsheets & databases
  • ๐Ÿ” Multi-step agent workflows (planning → executing → summarizing)

Bro, this opens up the door to full-fledged agentic AI dashboards — from assistants to analytics bots. Want me to prepare a **complete notebook + GitHub repo template** for this? Let’s go!

#9 ๐Ÿง  Machine Learning Dashboards in Streamlit (Regression + Classification + Charts)

Want to see your ML models in action with sliders, dropdowns, and live predictions? Streamlit makes that super easy — no frontend code, just Python! Let’s build interactive dashboards for both regression and classification tasks. ๐Ÿš€


1️⃣ Install Libraries


!pip install streamlit scikit-learn plotly pandas numpy

2️⃣ Start Your Streamlit App


import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.datasets import load_iris, fetch_california_housing
from sklearn.metrics import mean_squared_error, accuracy_score
import plotly.express as px

st.set_page_config(page_title="ML Dashboards", layout="wide")
st.title("๐Ÿง  Machine Learning Dashboard")
st.sidebar.header("⚙️ Choose Task")

task = st.sidebar.radio("Select Type:", ["Regression", "Classification"])

3️⃣ Regression Dashboard — California Housing


if task == "Regression":
    st.header("๐Ÿก California Housing — Linear Regression")
    data = fetch_california_housing(as_frame=True)
    df = data.frame

    st.write("### Dataset Preview")
    st.dataframe(df.head())

    X = df.drop("MedHouseVal", axis=1)
    y = df["MedHouseVal"]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    model = LinearRegression()
    model.fit(X_train, y_train)
    preds = model.predict(X_test)
    mse = mean_squared_error(y_test, preds)

    st.metric("Mean Squared Error", round(mse, 3))

    fig = px.scatter(x=y_test, y=preds, labels={'x':'Actual', 'y':'Predicted'}, title="Actual vs Predicted Values")
    st.plotly_chart(fig, use_container_width=True)

4️⃣ Classification Dashboard — Iris Dataset


if task == "Classification":
    st.header("๐ŸŒธ Iris Flower Classification — Logistic Regression")
    iris = load_iris(as_frame=True)
    df = iris.frame

    st.write("### Dataset Preview")
    st.dataframe(df.head())

    X = df.drop("target", axis=1)
    y = df["target"]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    model = LogisticRegression(max_iter=500)
    model.fit(X_train, y_train)
    preds = model.predict(X_test)
    acc = accuracy_score(y_test, preds)

    st.metric("Accuracy", f"{acc*100:.2f}%")

    fig = px.scatter_3d(df, x="sepal length (cm)", y="sepal width (cm)", z="petal length (cm)",
                        color=df["target"].map({0:"Setosa",1:"Versicolor",2:"Virginica"}),
                        title="3D Flower Visualization")
    st.plotly_chart(fig, use_container_width=True)

5️⃣ Add Real-Time User Prediction


if task == "Classification":
    st.subheader("๐Ÿ”ฎ Predict Flower Type")

    sl = st.slider("Sepal Length (cm)", 4.0, 8.0, 5.8)
    sw = st.slider("Sepal Width (cm)", 2.0, 4.5, 3.0)
    pl = st.slider("Petal Length (cm)", 1.0, 7.0, 4.3)
    pw = st.slider("Petal Width (cm)", 0.1, 2.5, 1.3)

    sample = np.array([[sl, sw, pl, pw]])
    pred = model.predict(sample)[0]
    species = iris.target_names[pred]

    st.success(f"๐ŸŒผ Predicted Flower: **{species}**")

6️⃣ Run the App

# Save the file as app.py
# Run this in terminal
streamlit run app.py  (or) python -m streamlit run app.py

Open the link Streamlit gives (usually http://localhost:8501) — and your ML dashboard is live ๐ŸŽฏ


Part of Response(s) should be like ๐Ÿ‘‡
Regression


Classification

✅ What You Learned

  • ⚙️ Use Streamlit for real-time model dashboards
  • ๐Ÿก Build a regression dashboard with metrics & charts
  • ๐ŸŒธ Add interactive classification UI with sliders
  • ๐Ÿ“Š Visualize results using Plotly

Now bro, you can turn any ML model into a live web app in under 50 lines of Python ๐Ÿ”ฅ Next up? “Streamlit + LangChain for Agentic AI Apps” — want me to make that next?

#8 Streamlit interactive dashboards

๐ŸŽฏ Streamlit for Data Apps — Build Dashboards in 10 Lines of Python

Tired of HTML and JS? Streamlit lets you create interactive dashboards with pure Python — no frontend code required! From charts to file uploads to ML model demos — it’s all possible in minutes. Let’s dive into the world of Streamlit! ๐Ÿš€


1️⃣ Install Streamlit


!pip install streamlit

Then launch the app with: streamlit run app.py

Just check in your terminal prompt cmd: python -m streamlit hell


2️⃣ Your First Streamlit App (10 Lines Only)


import streamlit as st
import pandas as pd
import numpy as np

st.title("๐Ÿš€ My First Streamlit Dashboard")
st.write("Hello, Data Scientists! ๐Ÿ‘‹")

data = pd.DataFrame(np.random.randn(10, 2), columns=["A", "B"])
st.line_chart(data)

Run it and open the browser link — boom ๐Ÿ’ฅ an interactive chart in seconds!

It it does not work, try in your project folder cmd prompt: python -m pip install --upgrade streamlit && python -m streamlit run t1.py


3️⃣ Adding Widgets


import streamlit as st

st.title("๐ŸŽ›️ Widgets in Action")

name = st.text_input("Enter your name:")
age = st.slider("Select your age", 10, 60, 25)
clicked = st.button("Greet Me")

if clicked:
    st.success(f"Hey {name}, you are {age} years old! ๐Ÿ˜„")

๐Ÿ‘‰ Streamlit automatically handles UI, state, and interactivity — no callbacks needed!


4️⃣ Displaying DataFrames and Charts


import streamlit as st
import pandas as pd
import plotly.express as px

st.title("๐Ÿ“ˆ Visualizing Data with Plotly")

df = px.data.gapminder().query("year == 2007")
continent = st.selectbox("Choose Continent", df["continent"].unique())

filtered_df = df[df["continent"] == continent]
fig = px.bar(filtered_df, x="country", y="gdpPercap", color="country", title=f"GDP per Capita in {continent}")
st.plotly_chart(fig)

5️⃣ File Upload Example


import streamlit as st
import pandas as pd

st.title("๐Ÿ“‚ CSV File Uploader")

file = st.file_uploader("Upload your CSV file", type=["csv"])
if file:
    df = pd.read_csv(file)
    st.write("Preview:")
    st.dataframe(df.head())

Perfect for quick data exploration dashboards ๐Ÿ”


6️⃣ Real-Time Metrics Dashboard


import streamlit as st
import numpy as np
import time

st.title("๐Ÿ“Š Real-Time Metrics Dashboard")

progress = st.progress(0)
status = st.empty()

for i in range(100):
    progress.progress(i + 1)
    status.text(f"Processing... {i + 1}%")
    time.sleep(0.05)

st.success("✅ Done!")


Part of Result 



7️⃣ Deploy to the Web (Free!)

๐Ÿš€ Host your app free on Streamlit Cloud — just connect your GitHub repo and click “Deploy”. It auto-runs your streamlit run app.py on the cloud ๐ŸŒ


✅ What You Learned

  • ๐Ÿ’ก Create dashboards in pure Python
  • ๐ŸŽจ Add charts, forms, and widgets easily
  • ๐Ÿ“ฆ Upload and visualize data
  • ๐Ÿš€ Deploy in minutes with Streamlit Cloud

Bro, now you can build a full-fledged **AI or ML dashboard** in under 30 lines of code ๐Ÿ˜Ž Next step? Try connecting Streamlit with your trained ML model for live predictions!



#5 Plotly Dashboards with Dash

๐Ÿ“Š Build Interactive Dashboards with Plotly Dash — No HTML Needed!

Dash is a Python framework for creating interactive web dashboards directly in Python — no need for HTML, CSS, or JavaScript. Perfect for Data Scientists who want to share visual insights quickly! ๐Ÿš€ Here’s a complete beginner-friendly guide with working examples.


1️⃣ Install Dash


# Install Dash (includes Plotly)
!pip install dash plotly

2️⃣ Basic Dash App — “Hello Dashboard”


from dash import Dash, html

# Create app
app = Dash(__name__)

# Layout (like HTML but written in Python)
app.layout = html.Div([
    html.H1("๐Ÿ“Š My First Dash App"),
    html.P("Hello, Data Scientists! ๐Ÿš€"),
])

# Run app
if __name__ == "__main__":
    app.run_server(debug=True)

➡️ Visit http://127.0.0.1:8050 in your browser to see your app live!


3️⃣ Adding Graphs with Plotly


from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd

# Sample data
df = px.data.gapminder().query("year == 2007")

# Create figure
fig = px.bar(df, x="continent", y="pop", color="continent", title="Population by Continent (2007)")

# App layout
app = Dash(__name__)
app.layout = html.Div([
    html.H1("๐ŸŒ Population Dashboard"),
    dcc.Graph(figure=fig)
])

if __name__ == "__main__":
    app.run_server(debug=True)

4️⃣ Interactive Dashboard with Callbacks


from dash import Dash, html, dcc, Input, Output
import plotly.express as px
import pandas as pd

df = px.data.gapminder()

app = Dash(__name__)

# Layout
app.layout = html.Div([
    html.H1("๐ŸŒŽ GDP vs Life Expectancy Dashboard"),
    dcc.Dropdown(
        id="year-dropdown",
        options=[{"label": y, "value": y} for y in sorted(df.year.unique())],
        value=2007
    ),
    dcc.Graph(id="scatter-chart")
])

# Callback — update chart based on selected year
@app.callback(
    Output("scatter-chart", "figure"),
    Input("year-dropdown", "value")
)
def update_chart(selected_year):
    filtered_df = df[df.year == selected_year]
    fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp", size="pop",
                     color="continent", hover_name="country", log_x=True,
                     title=f"GDP vs Life Expectancy ({selected_year})")
    return fig

if __name__ == "__main__":
    app.run_server(debug=True)

5️⃣ Multi-Page Dashboard (Advanced)


from dash import Dash, html, dcc, Input, Output
import plotly.express as px
import pandas as pd

df = px.data.gapminder()
app = Dash(__name__, suppress_callback_exceptions=True)

app.layout = html.Div([
    dcc.Location(id="url"),
    html.Div(id="page-content")
])

# Define pages
def home_page():
    return html.Div([
        html.H2("๐Ÿ  Home Page"),
        html.A("Go to GDP Dashboard", href="/gdp")
    ])

def gdp_page():
    return html.Div([
        html.H2("๐Ÿ“Š GDP Dashboard"),
        dcc.Dropdown(id="continent", options=[{"label": c, "value": c} for c in df.continent.unique()], value="Asia"),
        dcc.Graph(id="gdp-graph"),
        html.A("⬅ Back Home", href="/")
    ])

# Router callback
@app.callback(Output("page-content", "children"), Input("url", "pathname"))
def display_page(pathname):
    if pathname == "/gdp":
        return gdp_page()
    return home_page()

# Graph callback
@app.callback(Output("gdp-graph", "figure"), Input("continent", "value"))
def update_graph(continent):
    filtered_df = df[df.continent == continent]
    return px.line(filtered_df, x="year", y="gdpPercap", color="country", title=f"GDP Growth ({continent})")

if __name__ == "__main__":
    app.run_server(debug=True)

✅ What You Learned

  • ๐ŸŽจ Create dashboards using pure Python (no HTML/CSS needed)
  • ๐Ÿ“ˆ Add interactive Plotly charts easily
  • ๐Ÿ”„ Use callbacks for real-time interactivity
  • ๐Ÿงญ Build multi-page dashboards for large projects

๐Ÿ’ก Pro Tip: Host your Dash app on Render, Railway, or Streamlit Cloud for free — and share your live dashboards with anyone! ๐ŸŒ

Suggestion : Please use Visual Studio Code Editor 

Response 




#4 Plotly Interactive Visualizations for Data Scientists

๐Ÿ“ˆ Plotly Interactive Visualizations for Data Scientists

Plotly makes your charts interactive, dynamic, and stunningly modern — all with just a few lines of Python. Zoom, hover, and explore your data like never before! This post shows the most useful examples using plotly.express.


1️⃣ Install & Import Plotly


# Install Plotly (if not already installed)
!pip install plotly

import plotly.express as px
import pandas as pd

2️⃣ Line Chart — Trend Over Time


# Sample DataFrame
df = pd.DataFrame({
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    'Sales': [200, 250, 300, 400, 450, 500]
})

# Interactive Line Chart
fig = px.line(df, x='Month', y='Sales', title='Monthly Sales Trend', markers=True)
fig.show()

3️⃣ Bar Chart — Comparing Categories


df = pd.DataFrame({
    'Product': ['A', 'B', 'C', 'D'],
    'Revenue': [1200, 900, 1500, 1100]
})

fig = px.bar(df, x='Product', y='Revenue', color='Product',
             title='Revenue by Product', text='Revenue')
fig.update_traces(textposition='outside')
fig.show()

4️⃣ Scatter Plot — Data Relationship


# Built-in dataset
df = px.data.iris()

# Interactive scatter with hover info
fig = px.scatter(df, x='sepal_width', y='sepal_length',
                 color='species', size='petal_length',
                 hover_data=['petal_width'],
                 title='Iris Flower Data')
fig.show()

5️⃣ Pie Chart — Category Proportions


fig = px.pie(df, names='species', title='Iris Species Distribution', hole=0.3)
fig.show()

6️⃣ Box Plot — Distribution Analysis


fig = px.box(df, x='species', y='sepal_length', color='species',
             title='Sepal Length Distribution by Species')
fig.show()

7️⃣ Histogram — Frequency Distribution


fig = px.histogram(df, x='petal_length', nbins=20, color='species',
                   title='Petal Length Distribution')
fig.show()

8️⃣ Heatmap — Correlation Matrix


corr = df.corr(numeric_only=True)
fig = px.imshow(corr, text_auto=True, color_continuous_scale='viridis',
                title='Correlation Heatmap')
fig.show()

9️⃣ Geo Visualization — World Map


geo_df = px.data.gapminder().query("year == 2007")

fig = px.choropleth(
    geo_df,
    locations="iso_alpha",
    color="lifeExp",
    hover_name="country",
    title="๐ŸŒ Life Expectancy Around the World (2007)",
    color_continuous_scale=px.colors.sequential.Plasma
)
fig.show()

๐Ÿ”Ÿ Animated Chart — Population Growth Over Time


gapminder = px.data.gapminder()

fig = px.scatter(
    gapminder,
    x="gdpPercap",
    y="lifeExp",
    animation_frame="year",
    animation_group="country",
    size="pop",
    color="continent",
    hover_name="country",
    log_x=True,
    size_max=55,
    range_x=[100,100000],
    range_y=[25,90],
    title="๐ŸŒŽ Population Growth (1952–2007)"
)
fig.show()

๐Ÿ’ก Pro Tip: Use fig.write_html("chart.html") to save any Plotly chart as an interactive web page! Perfect for dashboards, portfolios, or blog embeds. ๐Ÿš€

#3 Matplotlib + Seaborn Basics

๐Ÿ“Š Matplotlib & Seaborn Visualizations for Beginners

Welcome to your Matplotlib and Seaborn visual guide! Learn how to create awesome charts — from basic line plots to colorful heatmaps — all with a copy button and syntax-highlighted code.


1️⃣ Importing Libraries


import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# Sample data
data = {
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    'Sales': [200, 240, 300, 350, 400, 450]
}
df = pd.DataFrame(data)

2️⃣ Line Plot with Matplotlib


plt.figure(figsize=(8, 4))
plt.plot(df['Month'], df['Sales'], marker='o', color='cyan', linewidth=2)
plt.title('Monthly Sales Growth')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.grid(True)
plt.show()

3️⃣ Bar Chart


plt.figure(figsize=(7, 4))
plt.bar(df['Month'], df['Sales'], color='orange')
plt.title('Sales by Month')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()

4️⃣ Scatter Plot


import numpy as np

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)

plt.scatter(x, y, c=colors, cmap='viridis', s=100)
plt.title('Random Scatter Plot')
plt.show()

5️⃣ Pie Chart


sizes = [30, 25, 20, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
plt.title('Category Distribution')
plt.show()

6️⃣ Histogram


data = np.random.randn(1000)

plt.hist(data, bins=30, color='purple', edgecolor='white')
plt.title('Histogram of Random Data')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()

7️⃣ Seaborn — Basic Styling


sns.set_theme(style="darkgrid")

# Sample DataFrame
tips = sns.load_dataset('tips')
tips.head()

8️⃣ Seaborn — Histogram & KDE


sns.histplot(tips['total_bill'], bins=20, kde=True, color='skyblue')
plt.title('Total Bill Distribution')
plt.show()

9️⃣ Seaborn — Scatter & Regression


sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex', height=5)
plt.title('Tips vs Total Bill')
plt.show()

๐Ÿ”Ÿ Seaborn — Heatmap


corr = tips.corr(numeric_only=True)
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title('Correlation Heatmap')
plt.show()

๐Ÿ’ก Tip: Use plt.style.use('seaborn-v0_8-dark') to instantly switch to modern dark themes. Combine Matplotlib + Seaborn = Pro-level plots in Python! ๐ŸŽจ

#2.e Numpy Basics

๐Ÿ”ข NumPy Concepts with Demo Programs

This blog covers essential NumPy concepts for data science and numerical computing. Each demo has syntax highlighting and a copy button for easy learning and sharing.


1. Creating NumPy Arrays


import numpy as np

# 1D array
arr1 = np.array([1, 2, 3, 4])
print("1D array:", arr1)

# 2D array
arr2 = np.array([[1, 2], [3, 4]])
print("2D array:\n", arr2)

# Using arange and linspace
arr_arange = np.arange(0, 10, 2)  # start, stop, step
arr_linspace = np.linspace(0, 1, 5)  # start, stop, number of points
print("arange:", arr_arange)
print("linspace:", arr_linspace)

# Array of zeros, ones, identity
zeros = np.zeros((2,3))
ones = np.ones((2,2))
identity = np.eye(3)
print("Zeros:\n", zeros)
print("Ones:\n", ones)
print("Identity:\n", identity)

2. Array Indexing and Slicing


# 1D array slicing
arr = np.array([10, 20, 30, 40, 50])
print("Original array:", arr)
print("Slice [1:4]:", arr[1:4])
print("Every 2nd element:", arr[::2])

# 2D array indexing
arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("Element at (0,2):", arr2d[0,2])
print("First row:", arr2d[0])
print("Second column:", arr2d[:,1])

3. Array Operations


a = np.array([1,2,3])
b = np.array([4,5,6])

# Element-wise operations
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)

# Universal functions
print("sqrt(a):", np.sqrt(a))
print("exp(a):", np.exp(a))
print("sin(a):", np.sin(a))

4. Array Aggregations


arr = np.array([[1,2,3],[4,5,6]])

print("Sum:", np.sum(arr))
print("Sum axis=0 (columns):", np.sum(arr, axis=0))
print("Sum axis=1 (rows):", np.sum(arr, axis=1))
print("Mean:", np.mean(arr))
print("Max:", np.max(arr))
print("Min:", np.min(arr))
print("Std dev:", np.std(arr))

5. Reshaping and Transpose


arr = np.arange(12)
print("Original array:", arr)

reshaped = arr.reshape(3,4)
print("Reshaped (3x4):\n", reshaped)

flattened = reshaped.flatten()
print("Flattened:", flattened)

print("Transpose:\n", reshaped.T)

6. Boolean Indexing and Filtering


arr = np.array([10, 15, 20, 25, 30])

# Boolean mask
mask = arr > 20
print("Mask:", mask)
print("Filtered array:", arr[mask])

# Or directly
print("Values > 20:", arr[arr > 20])

7. Random Numbers with NumPy


# Random numbers
rand_float = np.random.rand(5)  # uniform [0,1)
rand_int = np.random.randint(0, 10, size=5)
rand_norm = np.random.randn(5)  # standard normal
print("Random floats:", rand_float)
print("Random integers:", rand_int)
print("Random normal:", rand_norm)

8. Linear Algebra & Dot Products


A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])

# Matrix multiplication
dot = np.dot(A,B)
print("Dot product:\n", dot)

# Determinant and inverse
det = np.linalg.det(A)
inv = np.linalg.inv(A)
print("Determinant:", det)
print("Inverse:\n", inv)

9. Stacking Arrays


a = np.array([1,2,3])
b = np.array([4,5,6])

# Vertical and horizontal stacking
vstacked = np.vstack([a,b])
hstacked = np.hstack([a,b])
print("VStacked:\n", vstacked)
print("HStacked:", hstacked)

10. Saving and Loading Arrays


arr = np.arange(10)

# Save to file
np.save("my_array.npy", arr)

# Load back
loaded_arr = np.load("my_array.npy")
print("Loaded array:", loaded_arr)

✅ With these 10 demos, you now have a full **NumPy cheat sheet with practical code examples**, ready for learning !

#2 Pandas - Basics

๐Ÿผ Pandas Concepts with Demo Programs

This post covers essential Pandas concepts every data enthusiast should know — from creating DataFrames to filtering, grouping, and merging data. Each example includes syntax highlighting and a handy copy button!


1️⃣ Importing Pandas & Creating DataFrame


import pandas as pd

# Create a simple DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [25, 30, 35, 40],
    'City': ['Chennai', 'Bangalore', 'Delhi', 'Mumbai']
}

df = pd.DataFrame(data)
print(df)
df.to_csv('data.csv',index=False) # for next ex
2️⃣ Reading Data from CSV

# Read CSV file
df = pd.read_csv('data.csv')

# Display first 5 rows
print(df.head())

3️⃣ Data Selection — iloc & loc


# Select by row and column index
print(df.iloc[0, 1])

# Select by label
print(df.loc[0, 'Name'])

4️⃣ Filtering Rows


# Filter rows where Age > 30
filtered = df[df['Age'] > 30]
print(filtered)

5️⃣ GroupBy and Aggregations


# Group by City and get average Age
grouped = df.groupby('City')['Age'].mean()
print(grouped)

6️⃣ Sorting & Renaming Columns


# Sort by Age descending
df_sorted = df.sort_values(by='Age', ascending=False)
print(df_sorted)

# Rename column
df_renamed = df.rename(columns={'City': 'Location'})
print(df_renamed)

7️⃣ Handling Missing Data


# Fill missing values
df.fillna({'Age': df['Age'].mean()}, inplace=True)

# Drop rows with NaN
df.dropna(inplace=True)

8️⃣ Merging & Joining DataFrames


# Merge two DataFrames on 'Name'
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Score': [85, 90]})
df2 = pd.DataFrame({'Name': ['Bob', 'Charlie'], 'Rank': [2, 3]})

merged = pd.merge(df1, df2, on='Name', how='outer')
print(merged)

9️⃣ Pivot Tables


# Create a pivot table
pivot = pd.pivot_table(df, values='Age', index='City', aggfunc='mean')
print(pivot)

๐Ÿ”Ÿ Exporting Data


# Export DataFrame to CSV
df.to_csv('output.csv', index=False)
print("✅ Data exported successfully!")

๐Ÿ’ก Tip: Pandas + NumPy + Matplotlib = a powerful combo for Data Science beginners!

Please also refer Cook Book

#20b Python (run+edit in browser ^ all in one)

๐Ÿ Python Basics — 5 Interactive Modules Edit code live with syntax highlighting and click ▶ Run . Each module runs separately ...