Skip to content
Home » Posts » Exploring Python Libraries

Exploring Python Libraries

  • by

Python has a vast ecosystem of libraries and frameworks for various purposes. Some popular Python libraries include:

  1. NumPy: For numerical computing with arrays and matrices.
  2. Pandas: For data manipulation and analysis, especially with structured data.
  3. Matplotlib: For creating static, animated, and interactive visualizations.
  4. Scikit-learn: For machine learning tasks such as classification, regression, clustering, etc.
  5. TensorFlow and PyTorch: Deep learning libraries for building and training neural networks.
  6. Beautiful Soup: For web scraping and parsing HTML/XML documents.
  7. Django and Flask: Web frameworks for building web applications.
  8. SQLAlchemy: For working with SQL databases using Python.
  9. Requests: For making HTTP requests and working with APIs.
  10. OpenCV: For computer vision tasks like image and video processing.
  11. NLTK and Spacy: Natural language processing libraries for text analysis and processing.
  12. SciPy: For scientific and technical computing, including optimization, integration, interpolation, etc.

NumPy

import numpy as np

# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])

# Perform operations on the array
mean = np.mean(arr)
std_dev = np.std(arr)

print("Array:", arr)
print("Mean:", mean)
print("Standard Deviation:", std_dev)

Pandas

import pandas as pd

# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# Perform operations on the DataFrame
df_filtered = df[df['Age'] > 30]

print("Original DataFrame:")
print(df)
print("\nFiltered DataFrame:")
print(df_filtered)

Matplotlib

import matplotlib.pyplot as plt

# Create data
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 20, 12]

# Create a line plot
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()

Scikit-learn

from sklearn.linear_model import LinearRegression
import numpy as np

# Generate random data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([3, 5, 7, 9, 11])

# Fit a linear regression model
model = LinearRegression()
model.fit(X, y)

# Predict values
X_test = np.array([[6], [7]])
y_pred = model.predict(X_test)

print("Predicted values:", y_pred)

Of course, here are more examples for some other popular Python libraries:

TensorFlow

import tensorflow as tf

# Define a simple neural network model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(10, activation='relu', input_shape=(4,)),
    tf.keras.layers.Dense(1)
])

# Compile the model
model.compile(optimizer='adam', loss='mse')

# Generate random data
X = tf.random.normal((100, 4))
y = tf.random.normal((100, 1))

# Train the model
model.fit(X, y, epochs=10)

# Make predictions
predictions = model.predict(X[:5])
print("Predictions:", predictions)

Django

  1. First, install Django using pip: pip install django.
  2. Create a new Django project: django-admin startproject myproject.
  3. Create a new Django app: python manage.py startapp myapp.
# In myapp/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, Django!")

# In myproject/urls.py
from django.urls import path
from myapp import views

urlpatterns = [
    path('', views.index, name='index'),
]

# In myproject/settings.py
INSTALLED_APPS = [
    'myapp',
]

# Run the development server
# python manage.py runserver

Visit http://localhost:8000/ in your browser to see “Hello, Django!”.

Requests

import requests

# Make a GET request
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

# Check the response status code
if response.status_code == 200:
    # Print the JSON response content
    print("Response content:")
    print(response.json())
else:
    print("Error:", response.status_code)

NLTK

import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')

# Tokenize a sentence
sentence = "Natural language processing is interesting."
tokens = word_tokenize(sentence)

print("Tokens:", tokens)

Photo by Emil Widlund on Unsplash