Introduzione alle librerie di terze parti
Versione italiana
Le librerie di terze parti in Python sono uno dei punti di forza del linguaggio, poiché estendono le sue funzionalità in modo significativo. Di seguito è riportata un'introduzione ad alcune delle librerie più popolari e utili per vari scopi:
1. numpy
: Calcolo numerico e array multidimensionali
numpy
è una libreria fondamentale per il calcolo numerico in Python. Fornisce strutture dati efficienti come gli array multidimensionali e una vasta gamma di funzioni matematiche per operazioni veloci su grandi quantità di dati.
-
Caratteristiche principali:
- Array multidimensionali (
ndarray
). - Operazioni vettorializzate (evitano loop espliciti).
- Funzioni matematiche avanzate (algebra lineare, trasformate di Fourier, ecc.).
- Integrazione con altre librerie scientifiche.
- Array multidimensionali (
-
Esempio:
import numpy as np
# Creazione di un array
arr = np.array([1, 2, 3, 4, 5])
# Operazioni vettorializzate
print(arr * 2) # Output: [ 2 4 6 8 10]
# Creazione di una matrice
matrix = np.array([[1, 2], [3, 4]])
print(matrix)
2. pandas
: Manipolazione di dati strutturati (DataFrame)
pandas
è una libreria per la manipolazione e l'analisi di dati strutturati, come tabelle e serie temporali. Il suo oggetto principale è il DataFrame
, che rappresenta una tabella di dati con righe e colonne.
-
Caratteristiche principali:
- Strutture dati:
Series
(colonne) eDataFrame
(tabelle). - Operazioni di lettura/scrittura su file (CSV, Excel, SQL, ecc.).
- Pulizia, trasformazione e aggregazione dei dati.
- Supporto per dati mancanti.
- Strutture dati:
-
Esempio:
import pandas as pd
# Creazione di un DataFrame
data = {'Nome': ['Alice', 'Bob', 'Charlie'], 'Età': [25, 30, 35]}
df = pd.DataFrame(data)
# Visualizzazione dei dati
print(df)
# Output:
# Nome Età
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
3. matplotlib
e seaborn
: Visualizzazione dei dati
matplotlib
è una libreria per la creazione di grafici e visualizzazioni, mentre seaborn
è costruita su matplotlib
e offre un'interfaccia più semplice e grafici più attraenti.
-
Caratteristiche principali:
- Creazione di grafici 2D e 3D.
- Personalizzazione di grafici (colori, stili, etichette).
- Grafici avanzati con
seaborn
(heatmap, pairplot, ecc.).
-
Esempio con
matplotlib
:
import matplotlib.pyplot as plt
# Dati
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Creazione di un grafico
plt.plot(x, y, marker='o')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Grafico di esempio')
plt.show()
- Esempio con
seaborn
:
import seaborn as sns
import pandas as pd
# Dati
data = pd.DataFrame({'X': [1, 2, 3, 4, 5], 'Y': [10, 20, 25, 30, 40]})
# Creazione di un grafico
sns.lineplot(x='X', y='Y', data=data)
plt.show()
4. requests
: Richieste HTTP
requests
è una libreria per effettuare richieste HTTP in modo semplice e intuitivo. È ampiamente utilizzata per interagire con API web.
-
Caratteristiche principali:
- Invio di richieste GET, POST, PUT, DELETE, ecc.
- Gestione di parametri, intestazioni e autenticazione.
- Lettura di risposte JSON.
-
Esempio:
import requests
# Richiesta GET
response = requests.get('https://api.github.com')
# Lettura della risposta
print(response.status_code) # Codice di stato (es. 200)
print(response.json()) # Dati JSON restituiti
5. flask
o django
: Introduzione al web development
Sia flask
che django
sono framework per lo sviluppo di applicazioni web in Python.
-
flask
:- Microframework leggero e flessibile.
- Ideale per applicazioni piccole o medie.
- Richiede configurazione manuale per funzionalità avanzate.
-
django
:- Framework full-stack con funzionalità integrate (admin, ORM, autenticazione).
- Ideale per applicazioni complesse e scalabili.
- Maggiore complessità rispetto a
flask
.
-
Esempio con
flask
:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Ciao, mondo!"
if __name__ == '__main__':
app.run(debug=True)
- Esempio con
django
:- Installa Django:
pip install django
. - Crea un progetto:
django-admin startproject myproject
. - Avvia il server:
python manage.py runserver
.
- Installa Django:
English version
Introduction to Third-Party Libraries
Third-party libraries in Python are one of the strengths of the language, as they extend its functionality significantly. Here is an introduction to some of the most popular and useful libraries for various purposes:
1. numpy
: Numerical Computing and Multidimensional Arrays
numpy
is a fundamental library for numerical computation in Python. It provides efficient data structures such as multidimensional arrays and a wide range of mathematical functions for fast operations on large amounts of data.
-
Key Features:
-
Multidimensional arrays (
ndarray
). -
Vectorized operations (avoid explicit loops).
-
Advanced mathematical functions (linear algebra, Fourier transforms, etc.).
-
Integration with other scientific libraries.
-
Example:
import numpy as np
# Creating an array
arr = np.array([1, 2, 3, 4, 5])
# Vectorized operations
print(arr * 2) # Output: [ 2 4 6 8 10]
# Creating a matrix
matrix = np.array([[1, 2], [3, 4]])
print(matrix)
2. pandas
: Structured data manipulation (DataFrame)
pandas
is a library for manipulating and analyzing structured data, such as tables and time series. Its main object is the DataFrame
, which represents a data table with rows and columns.
-
Key Features:
-
Data structures:
Series
(columns) andDataFrame
(tables). -
Read/write operations on files (CSV, Excel, SQL, etc.).
-
Data cleaning, transformation and aggregation.
-
Support for missing data.
-
Example:
import pandas as pd
# Creating a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# Visualizing the data
print(df)
# Output:
# Name Age
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
3. matplotlib
and seaborn
: Visualizing the data
matplotlib
is a library for creating graphs and visualizations, while seaborn
is built on top of matplotlib
and offers a simpler interface and more attractive graphs.
-
Key Features:
-
Creating 2D and 3D graphs.
-
Customization of graphs (colors, styles, labels).
-
Advanced graphs with
seaborn
(heatmap, pairplot, etc.). -
Example with
matplotlib
:
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Creating a plot
plt.plot(x, y, marker='o')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Sample plot')
plt.show()
- Example with
seaborn
:
import seaborn as sns
import pandas as pd
# Data
data = pd.DataFrame({'X': [1, 2, 3, 4, 5], 'Y': [10, 20, 25, 30, 40]})
# Creating a graph
sns.lineplot(x='X', y='Y', data=data)
plt.show()
4. requests
: HTTP Requests
requests
is a library for making HTTP requests in a simple and intuitive way. It is widely used to interact with web APIs.
-
Key Features:
-
Sending GET, POST, PUT, DELETE requests, etc.
-
Handling parameters, headers, and authentication.
-
Reading JSON responses.
-
Example:
import requests
# GET request
response = requests.get('https://api.github.com')
# Reading the response
print(response.status_code) # Status code (e.g. 200)
print(response.json()) # JSON data returned
5. flask
or django
: Introduction to web development
Both flask
and django
are frameworks for developing web applications in Python.
-
flask
: -
Lightweight and flexible microframework.
-
Ideal for small to medium applications.
-
Requires manual configuration for advanced features.
-
django
: -
Full-stack framework with built-in features (admin, ORM, authentication).
-
Ideal for complex and scalable applications.
-
More complex than
flask
. -
Example with
flask
:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, world!"
if __name__ == '__main__':
app.run(debug=True)
- Example with
django
:
- Install Django:
pip install django
. - Create a project:
django-admin startproject myproject
. - Start the server:
python manage.py runserver
.
Commenti
Posta un commento