学习Python,常用的这22个库怎能不掌握?("Python学习必掌握:这22个常用库你都知道吗?")

原创
ithorizon 6个月前 (10-20) 阅读数 19 #后端开发

Python学习必掌握:这22个常用库你都知道吗?

Python学习必掌握:这22个常用库你都知道吗?

Python作为一种有力的编程语言,其拥有充足的第三方库,可以帮助我们敏捷地实现各种功能。以下是22个常用的Python库,掌握它们将大大节约你的编程高效能。

1. NumPy

NumPy是一个有力的Python库,核心用于对多维数组执行计算。它是科学计算的基础库,提供了高效的数组操作。

import numpy as np

a = np.array([1, 2, 3])

print(a)

2. Pandas

Pandas是基于NumPy构建的库,用于数据处理和清洗。它提供了DataFrame对象,可以方便地处理表格数据。

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

print(df)

3. Matplotlib

Matplotlib是一个用于绘制图表的库,可以生成高质量的图形。它赞成多种图表类型,包括线图、条形图、散点图等。

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])

plt.show()

4. Scikit-learn

Scikit-learn是一个用于数据挖掘和数据分析的库,提供了许多机器学习算法的实现。

from sklearn.linear_model import LogisticRegression

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LogisticRegression()

model.fit(X_train, y_train)

5. TensorFlow

TensorFlow是一个用于深度学习的开源库,由Google开发。它赞成多种深度学习模型,包括卷积神经网络、循环神经网络等。

import tensorflow as tf

model = tf.keras.Sequential([

tf.keras.layers.Dense(10, activation='relu', input_shape=(784,)),

tf.keras.layers.Dense(10, activation='softmax')

])

model.compile(optimizer='adam',

loss='sparse_categorical_crossentropy',

metrics=['accuracy'])

6. Keras

Keras是一个高级神经网络API,可以运行在TensorFlow、CNTK或Theano之上。它简化了深度学习模型的设计和训练。

from keras.models import Sequential

from keras.layers import Dense

model = Sequential()

model.add(Dense(10, input_dim=784, activation='relu'))

model.add(Dense(10, activation='softmax'))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

7. Scipy

Scipy是一个用于科学计算的库,它基于NumPy,提供了许多用于优化、积分、插值等功能的模块。

from scipy.optimize import minimize

def rosen(x):

return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)

x0 = [1.2, 1.2, 1.2, 1.2, 1.2]

res = minimize(rosen, x0, method='BFGS')

print(res.x)

8. Statsmodels

Statsmodels是一个Python模块,提供了估计和测试统计模型的类和函数。

import statsmodels.api as sm

x = [1, 2, 3, 4, 5]

y = [2, 3, 5, 7, 11]

X = sm.add_constant(x)

model = sm.OLS(y, X).fit()

print(model.summary())

9. Seaborn

Seaborn是基于Matplotlib的另一个绘图库,它提供了更高级的接口,用于绘制吸引人的统计图表。

import seaborn as sns

tips = sns.load_dataset("tips")

sns.barplot(x="day", y="total_bill", data=tips)

sns.show()

10. BeautifulSoup

BeautifulSoup是一个用于解析HTML和XML文档的库,它可以帮助我们提取网页中的数据。

from bs4 import BeautifulSoup

html_doc = """

The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were

Elsie,

Lacie and

Tillie;

and they lived at the bottom of a well.

...

"""

soup = BeautifulSoup(html_doc, 'html.parser')

print(soup.prettify())

11. requests

requests是一个简洁的HTTP库,用于发送各种HTTP请求。它允许浏览器和服务器之间的通信变得简洁。

import requests

response = requests.get('https://api.github.com')

print(response.text)

12. Flask

Flask是一个轻量级的Web框架,用于敏捷构建Web应用程序。

from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello():

return "Hello, World!"

if __name__ == '__main__':

app.run()

13. Django

Django是一个高级的Python Web框架,鼓励敏捷开发和干净、实用的设计。

from django.http import HttpResponse

from django.views.decorators.http import require_http_methods

@require_http_methods(["GET"])

def hello(request):

return HttpResponse('Hello, World!')

14. SQLAlchemy

SQLAlchemy是一个SQL工具包和对象关系映射(ORM)框架,用于数据库交互。

from sqlalchemy import create_engine, Column, Integer, String

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):

__tablename__ = 'users'

id = Column(Integer, primary_key=True)

name = Column(String)

engine = create_engine('sqlite:///:memory:')

Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)

session = Session()

new_user = User(name='John Doe')

session.add(new_user)

session.commit()

15. Celery

Celery是一个异步任务队列/作业队列,基于分布式消息传递。

from celery import Celery

app = Celery('tasks', broker='pyamqp://guest@localhost//')

@app.task

def add(x, y):

return x + y

16. Pillow

Pillow是Python Imaging Library(PIL)的一个活跃的分支,用于图像处理。

from PIL import Image

img = Image.open('input.jpg')

img.show()

17. Scrapy

Scrapy是一个用于网页抓取和提取数据的框架。

import scrapy

class QuotesSpider(scrapy.Spider):

name = "quotes"

start_urls = [

'http://quotes.toscrape.com/tag/happiness/',

]

def parse(self, response):

for quote in response.css('div.quote'):

yield {

'text': quote.css('span.text::text').get(),

'author': quote.css('small.author::text').get(),

'tags': quote.css('a.tag::text').getall(),

}

18. Pygame

Pygame是一个用于开发游戏的Python模块,它提供了游戏开发所需的功能。

import pygame

pygame.init()

screen = pygame.display.set_mode((640, 480))

done = False

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

pygame.display.flip()

pygame.quit()

19. NetworkX

NetworkX是一个用于创建、操作和研究繁复网络的库。

import networkx as nx

G = nx.Graph()

G.add_edge(1, 2)

G.add_edge(1, 3)

print(G.nodes())

print(G.edges())

20. Matplotlib

Matplotlib是一个用于绘制图表的库,可以生成高质量的图形。

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])

plt.show()

21. PyTorch

PyTorch是一个流行的深度学习框架,它提供了灵活的动态计算图。

import torch

import torch.nn as nn

model = nn.Sequential(

nn.Linear(784, 128),

nn.ReLU(),

nn.Linear(128, 10),

nn.LogSoftmax(dim=1)

)

22. Jupyter Notebook

Jupyter Notebook是一个交互式计算环境,赞成超过40种编程语言,包括Python。

# 在Jupyter Notebook中执行

print("Hello, World!")

以上22个Python库涵盖了数据处理、数据可视化、机器学习、Web开发、图像处理等多个领域。掌握这些库,将使你的Python编程之路更加顺畅。


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: 后端开发


热门