UCONN

UCONN
UCONN

Python Libraries

 Python Libraries


Python libraries are a vast collection of mostly open source libraries that can be used by project development. These libraries allow for rapid development by providing pre-coded modules for functionality such as  sending emails or developing web interfaces.


Libraries are written by individuals, corporations, and non-profit foundations. Developers see a need and usually build open-source solutions for the python community to use.


Modules are single .py files containing functions and variables, Packages are folders are a collection of these modules and Libraries are a collection of these packages.


Libraries need to first be installed into your development environment, then imported by each individual python .py program and executed when the program is called.


The pip command (Python Package Index) is written in python and used as a package-management system. It installs these libraries from various python third party organizations for local development system use.

After the pip install, the python import keyword is used inside your python program for use.


Below is a description of some of the main python used libraries.


Data Science



NumPy library : Provides modules for efficient multi-dimensional array handling.

Pandas library: Used for data manipulation and analysis leveraging the concept of DataFrames.

Scikit-learn library: Used for machine learning concepts like regression and classification.

TensorFlow & PyTorch: Used for deep learning and AI models. models.

We will now focus on NumPy and Pandas and look at the ML libraries later.


NumPy


The NumPy library supports large, multi-dimensional arrays and matrices,and mathematical functions to act on these arrays.


NumPy arrays are much faster and have more functionality than traditional python lists and provide extensive capabilities on machine learning and data science examples.


Install numpy:


$ pip3 install numpy

Note: It may already be installed by default

Python program numpy_example.py

john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 num.py

[1 2 3 4 5]

<class 'numpy.ndarray'>

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 


Python program numpy_example.py

===================================================

#import numpy library

import numpy as np

#customer details

name = input("Name: ")

address = input("Address: ")

#data in numpy (np) arrays

items = np.array(['Plates', 'Cups'])

prices = np.array([2, 4])

#quantities

num_plates = int(input("How many plates? "))

num_cups = int(input("How many cups? "))

#store quantities in a numpy array

quantities = np.array([num_plates, num_cups])

#calculate total for each item and overall total

totals = prices * quantities

total_cost = np.sum(totals)

#results

print("\nCustomer Information:")

print(f"Name: {name}")

print(f"Address: {address}")

print("\nInvoice:")

for i, item in enumerate(items): #iterate through numpy array to print result

    print(f"{item}: Quantity = {quantities[i]}, Unit Price = ${prices[i]}, Total = ${totals[i]}")

print(f"\nTotal Amount Due: ${total_cost}")


===================================================

Results


john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 numpy_example.py 

Name: John Iacovacci

Address: 55 Daffodil Road

How many plates? 4

How many cups? 4


Customer Information:

Name: John Iacovacci

Address: 55 Daffodil Road


Invoice:

Plates: Quantity = 4, Unit Price = $2, Total = $8

Cups: Quantity = 4, Unit Price = $4, Total = $16


Total Amount Due: $24

john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ 


Pandas


The Pandas library was designed for data manipulation and analysis. It provides data structures and operations for table manipulation.


Built-in tools to clean data for accurate processing. Very fast parts written in C programming language. Can read data from multiple formats and transform data for easy integration.

Install pandas


john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ pip3 install pandas

Defaulting to user installation because normal site-packages is not writeable

Collecting pandas

  Downloading pandas-2.2.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (13.1 MB)

     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.1/13.1 MB 18.3 MB/s eta 0:00:00

Requirement already satisfied: numpy>=1.22.4 in /usr/local/lib/python3.10/dist-packages (from pandas) (1.26.4)

Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.10/dist-packages (from pandas) (2.9.0.post0)

Collecting tzdata>=2022.7

  Downloading tzdata-2024.1-py2.py3-none-any.whl (345 kB)

     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 345.4/345.4 KB 26.6 MB/s eta 0:00:00

Collecting pytz>=2020.1

  Downloading pytz-2024.2-py2.py3-none-any.whl (508 kB)

     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 508.0/508.0 KB 27.1 MB/s eta 0:00:00

Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)

Installing collected packages: pytz, tzdata, pandas

Successfully installed pandas-2.2.3 pytz-2024.2 tzdata-2024.1


Python program pandas_example.py

===================================================

#!/usr/bin/python3

#import pandas library

import pandas as pd


#customer details

name = input("Name: ")

address = input("Address: ")


#item data, name and price

data = {

    'Item': ['Plates', 'Cups'],

    'Price': [2, 4]

}

df = pd.DataFrame(data) #dataframe


#quantities

num_plates = int(input("How many plates? "))

num_cups = int(input("How many cups? "))


#add quantities to the DataFrame

df['Quantity'] = [num_plates, num_cups]


#calculate total for each item and overall total

df['Total'] = df['Price'] * df['Quantity']

total_cost = df['Total'].sum()


#results

print(f"\n{name}\n{address}")

print(df[['Item', 'Quantity', 'Total']])

print(f"Amount Due = ${total_cost}")


====================================================

Results

john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 numpy_example.py 

Name: John Iacovacci

Address: 55 Daffodil Road

How many plates? 4

How many cups? 4


Customer Information:

Name: John Iacovacci

Address: 55 Daffodil Road


Invoice:

Plates: Quantity = 4, Unit Price = $2, Total = $8

Cups: Quantity = 4, Unit Price = $4, Total = $16


Total Amount Due: $24

john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 pandas_example.py 

Name: John Iacovacci

Address: 55 Daffodil Road

How many plates? 4

How many cups? 4


John Iacovacci

55 Daffodil Road

     Item  Quantity  Total

0  Plates         4      8

1    Cups         4     16

Amount Due = $24

john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ 


Data Visualization


Observing information trends is an important part of data analytics. This is done by creating graphs and charts where users can detect patterns that appear in the data. A stock price with a downward trend may cause a trader to wait until the chart stabilizes before buying.


Matplotlib


Matplotlib is one of the main tools that python developers use to produce charts and graphs for data visualization. The library is designed to generate images based upon these graphs. A common use would be a traditional X and Y data point access. It can create plots, histograms, bar charts, scatter plots, etc., with small amounts of code..


====================================================

import pandas as pd                  # Data frame

from datetime import datetime

from matplotlib import pyplot as plt # Plotting Library

from google.cloud import storage     # Leverage Google Storage Buckets


#Google Cloud project ID

# use  your project ID from Google cloud

PROJECT_ID = 'cloud-project-examples'


# The ID of your GCS bucket (bucket name)

bucket_name = "cloud-storage-exam"


storage_client = storage.Client()

bucket = storage_client.bucket(bucket_name)


raw_data = [

    ("1/28/2026", 481.63),

    ("1/29/2026", 433.5),

    ("1/30/2026", 430.29),

    ("2/2/2026", 423.37),

    ("2/3/2026", 411.21),

    ("2/4/2026", 414.19),

    ("2/5/2026", 393.67),

    ("2/6/2026", 401.14)

]


# Parse dates using %m/%d/%Y (Month/Day/Year)

dates = [datetime.strptime(d[0], "%m/%d/%Y") for d in raw_data]

prices = [d[1] for d in raw_data]


# Plotting

plt.figure(figsize=(10, 5))

plt.plot(dates, prices, marker='o', linestyle='-', color='#e63946', linewidth=2)


# Styling

plt.title('Daily Price MSFT (Jan - Feb 2026)', fontsize=14)

plt.xlabel('Date', fontsize=12)

plt.ylabel('Price ($)', fontsize=12)

plt.grid(True, alpha=0.3)


# Rotate labels so they don't overlap

plt.xticks(rotation=45)

plt.tight_layout()


# Show results

plt.show()

plt.savefig('msft_prc.png')


# send plot file to your bucket

plot_filename = 'msft_prc.png'

destination_blob_name = f'{plot_filename}'

source_file_name = 'msft_prc.png'

blob = bucket.blob(destination_blob_name)

blob.upload_from_filename(source_file_name)  #upload file to specified destination

print(f'File {source_file_name} uploaded to {destination_blob_name}.')


====================================================


Had the output file moved to a public storage bucket.





No comments:

Post a Comment

Assignment #7 due 4/8/2026

  Take or use picture of a document(piece of mail) or any picture that has words. Use the https://uconnstamfordslp.blogspot.com/p/google-api...