UCONN

UCONN
UCONN

Python Libraries

 Python Libraries


Python was designed to be highly extensible via modules. 

This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. 


PIP

pip is a package-management system written in Python and is used to install and manage software packages. The Python Software Foundation recommends using pip for installing Python applications and its dependencies during deployment.


Install numpy:

$ pip3 install numpy

Note: It may already be installed by default

NumPy


NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

Python lists are excellent, general-purpose containers. They can be “heterogeneous”, meaning that they can contain elements of a variety of types, and they are quite fast when used to perform individual operations on a handful of elements.

NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.

Useful for Data Science and Machine learning.

Numpy can do everything python lists can do and much more.

Some applications include mathematics, plotting and machine learning.

Works well with other libraries like Pandas and Tensorflow.


Allowing for efficient data manipulation as well but its main use case involves multi-dimensional arrays and vectorized operations, which are faster and more efficient than using standard Python loops.


The import and from statements, used to import modules whose functions or variables can be used in the current program


Python program num.py

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

#!/usr/bin/python3

import numpy as np

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

print(arr)

print(type(arr))


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

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 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 (uconn-engr)$ python3 numpy_example.py

Name: John Iacovacci

Address: 55 Daffodil Road

How many plates? 2

How many cups? 2


Customer Information:

Name: John Iacovacci

Address: 55 Daffodil Road


Invoice:

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

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


Total Amount Due: $12

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



Pandas


Pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series.


Python library used for working with data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was created by Wes McKinney in 2008.

Provides fast, flexible, and expressive data structures designed to make working with "relational" or "labeled" data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Additionally, it has the broader goal of becoming the most powerful and flexible open source data analysis / manipulation tool available in any language. 

Pandas provides adaptable data structures with powerful instruments for data indexing, selecting, and manipulating which sidesteps the need for complex programming methods. You can easily convert CSV, Excel, SPSS (Statistical Package for the Social Sciences) files and SQL databases into DataFrames.

Install pandas

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 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

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


Python program pan.py

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

#!/usr/bin/python3

import pandas as pd


mydataset = {

  'cars': ["BMW", "Volvo", "Ford"],

  'passings': [3, 7, 2]

}


myvar = pd.DataFrame(mydataset)


print(myvar)

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

Results

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

    cars  passings

0    BMW         3

1  Volvo         7

2   Ford         2

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


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 (uconn-engr)$ 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 (uconn-engr)$ 

Matplotlib

Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.

Popular data visualization library in Python. It's often used for creating static, interactive, and animated visualizations in Python. Matplotlib allows you to generate plots, histograms, bar charts, scatter plots, etc., with just a few lines of code.

Matplotlib is a low level graph plotting library in python that serves as a visualization utility. Created by John D. Hunter,  open source and can be used freely. Mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform compatibility.

matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.




Python program mat.py

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

import matplotlib.pyplot as plt  

import numpy as np  


# Data for plotting

t = np.arange(0.0, 2.0, 0.01# Create an array of values t from 0 to 2 , with a step size of 0.01

s = 1 + np.sin(2 * np.pi * t)  # Calculate the s values (sin(2*pi*t)) and add 1 to shift the curve vertically


fig, ax = plt.subplots()  # Create a figure and a set of subplots (returns a figure and axis object)

ax.plot(t, s)  # Plot the time values 't' on the x-axis and the sine values 's' on the y-axis


# Set axis labels and title

ax.set(xlabel='x-axis', ylabel='y-axis', title='Simple Plot Example'# Label the x-axis, y-axis, and set a title for the plot

ax.grid()  # Add a grid to the plot for better visual reference



fig.savefig("test.png"# Save the figure to a file named "test.png"

plt.show()  # Display the plot window to the user

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











No comments:

Post a Comment

Disable Billing

Search for Billing Manage billing accounts Go to MYPROJECTS CLICK ON THE 3 BUTTON Actions Then hit disable