Python has a rich ecosystem of libraries. They cater to diverse applications such as data analysis, machine learning, and web development. Furthermore, they support more applications. Below is a categorized list of important Python libraries with examples of how to use them.
1. Data Manipulation and Analysis
Pandas
Used for data manipulation and analysis.
import pandas as pd # Create a DataFrame data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) print(df.head()) # View the first few rows
NumPy
For numerical computations and working with arrays.
import numpy as np # Create a NumPy array array = np.array([1, 2, 3, 4]) print(np.mean(array)) # Compute the mean
2. Visualization
Matplotlib
Basic plotting library for data visualization.
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 20, 25, 30] plt.plot(x, y) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Line Plot") plt.show()
Seaborn
High-level data visualization library built on Matplotlib.
import seaborn as sns import pandas as pd # Sample data data = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Values': [10, 20, 15]}) sns.barplot(x='Category', y='Values', data=data) plt.show()
3. Machine Learning
Scikit-learn
A robust library for machine learning tasks.
from sklearn.linear_model import LinearRegression
# Model and data
model = LinearRegression()
X = [[1], [2], [3]]
y = [1, 2, 3]
model.fit(X, y)
print(model.predict([[4]])) # Predict new value
TensorFlow
A powerful library for deep learning.
import tensorflow as tf # Simple constant in TensorFlow x = tf.constant([5, 6, 7]) print(x.numpy()) # Output: [5 6 7]
4. Web Development
Flask
Microframework for building web applications.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello, Flask!" if __name__ == "__main__": app.run(debug=True)
Django
A full-stack framework for web development.
- Use
django-admin startproject <project_name>
to initialize a project.
5. Data Science and Natural Language Processing
NLTK
For natural language processing.
import nltk from nltk.tokenize import word_tokenize sentence = "This is an example sentence." print(word_tokenize(sentence))
SpaCy
Efficient NLP library.
import spacy nlp = spacy.load("en_core_web_sm") doc = nlp("Natural language processing is fun!") for token in doc: print(token.text, token.pos_)
6. Web Scraping
BeautifulSoup
For parsing HTML and XML documents.
from bs4 import BeautifulSoup html = "<html><body><h1>Hello, World!</h1></body></html>" soup = BeautifulSoup(html, 'html.parser') print(soup.h1.text) # Output: Hello, World!
Requests
For making HTTP requests.
import requests response = requests.get("https://example.com") print(response.status_code) # Check the status code
7. Automation and Productivity
Selenium
Automates browser tasks.
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://example.com") print(driver.title) # Get the page title driver.quit()
OpenPyXL
For Excel file manipulation.
from openpyxl import Workbook wb = Workbook() sheet = wb.active sheet["A1"] = "Hello" wb.save("example.xlsx")
8. Graphs and Networks
NetworkX
For graph creation and manipulation.
import networkx as nx G = nx.Graph() G.add_edge("A", "B") print(G.edges) # Output: [('A', 'B')]
9. Testing
Pytest
For unit testing.
def add(x, y): return x + y def test_add(): assert add(2, 3) == 5
10. Other Specialized Libraries
OpenCV (Computer Vision):
import cv2 image = cv2.imread("example.jpg") cv2.imshow("Image", image) cv2.waitKey(0) cv2.destroyAllWindows()
PyTorch (Deep Learning):
import torch x = torch.tensor([1.0, 2.0]) print(x * 2)
These libraries represent just a fraction of the Python ecosystem. Each library has extensive documentation and community support to help you get started.
Discover more from Technology with Vivek Johari
Subscribe to get the latest posts sent to your email.