2025 最新出爐!15 個 Python 庫帶你飛
在Python的技術生態中,豐富多樣的庫是其一大亮點,這些出色的庫大大拓展了Python的應用邊界,堪稱改變編程格局的“利器”。當下,技術迭代日新月異,若想在2025年的編程領域中搶占先機,有幾款極具變革性的現代庫不容錯過。
1.Polars——極速數據幀庫
Polars是用Rust編寫的超快速數據幀庫,用于處理結構化數據。
圖片
優勢:Polars比Pandas快10到100倍。支持對大型數據集進行延遲求值,并且能與Apache Arrow原生協作。
文檔:https://docs.pola.rs/
安裝:
pip install polars
示例:以下是使用Polars創建數據幀的簡單示例:
import polars as pl
import datetime as dt
df = pl.DataFrame(
{
"name": ["Alice Archer", "Ben Brown", "Chloe Cooper", "Daniel Donovan"],
"birthdate": [
dt.date(1997, 1, 10),
dt.date(1985, 2, 15),
dt.date(1983, 3, 22),
dt.date(1981, 4, 30),
],
"weight": [57.9, 72.5, 53.6, 83.1], # (kg)
"height": [1.56, 1.77, 1.65, 1.75], # (m)
}
)
print(df)
輸出結果:
shape: (4, 4)
┌────────────────┬────────────┬────────┬────────┐
│ name ┆ birthdate ┆ weight ┆ height │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ date ┆ f64 ┆ f64 │
╞════════════════╪════════════╪════════╪════════╡
│ Alice Archer ┆ 1997-01-10 ┆ 57.9 ┆ 1.56 │
│ Ben Brown ┆ 1985-02-15 ┆ 72.5 ┆ 1.77 │
│ Chloe Cooper ┆ 1983-03-22 ┆ 53.6 ┆ 1.65 │
│ Daniel Donovan ┆ 1981-04-30 ┆ 83.1 ┆ 1.75 │
└────────────────┴────────────┴────────┴────────┘
2.Ruff——最快的Python格式化和代碼檢查工具
Ruff是基于 Rust 語言編寫的超快速代碼檢查工具,其設計初衷便是憑借自身強大功能,以 “一器之力” 取代 Flake8、Black 和 isort 這幾款傳統工具,為開發者提供更高效、便捷的代碼檢查與格式化解決方案 。
圖片
優勢:它比Flake8快20倍,支持自動修復問題,兼具格式化和代碼檢查功能。
文檔:https://docs.astral.sh/ruff/
安裝:
pip install ruff
示例:我們可以使用uv
初始化一個項目:
uv init --lib demo
這條命令會創建一個具有以下結構的Python項目:
demo
├── README.md
├── pyproject.toml
└── src
└── demo
├── __init__.py
└── py.typed
然后,將src/demo/__init__.py
的內容替換為以下代碼:
from typing import Iterable
import os
def sum_even_numbers(numbers: Iterable[int]) -> int:
"""給定一個整數的可迭代對象,返回其中所有偶數的和。"""
return sum(
num for num in numbers
if num % 2 == 0
)
接下來,將Ruff添加到項目中:
uv add --dev ruff
然后,可以通過uv run ruff check
在項目上運行Ruff代碼檢查:
$ uv run ruff check
src/numbers/__init__.py:3:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 fixable with the `--fix` option.
通過運行ruff check --fix
自動解決這個問題:
$ uv run ruff check --fix
Found 1 error (1 fixed, 0 remaining).
3.PyScript——在瀏覽器中運行Python
PyScript讓開發者可以在瀏覽器中編寫和執行Python代碼,類似于JavaScript。
優勢:PyScript支持開發基于Python的網頁應用,可直接在HTML中使用,無需后端。
文檔:https://docs.pyscript.net/2025.2.4/
安裝:無需安裝PyScript,只需在HTML文檔的<head>
標簽中添加一個<script>
和鏈接標簽即可。
<!-- PyScript CSS -->
<link rel="stylesheet" >
<!-- 此腳本標簽用于啟動PyScript -->
<script type="module" src="https://pyscript.net/releases/2025.2.4/core.js"></script>
示例:創建一個簡單的.html
文件,并使用<py-script>
標簽編寫Python代碼。
<!doctype html>
<html>
<head>
<!-- 推薦的元標簽 -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- PyScript CSS -->
<link rel="stylesheet" >
<!-- 此腳本標簽用于啟動PyScript -->
<script type="module" src="https://pyscript.net/releases/2025.2.4/core.js"></script>
</head>
<body>
<!-- 現在可以使用<py-script>標簽在其中編寫Python代碼 -->
<py-script>
import sys
from pyscript import display
display(sys.version)
</py-script>
</body>
</html>
4.Pandera——用于Pandas的數據驗證工具
Pandera通過基于模式的驗證方式,幫助驗證Pandas的數據幀(DataFrames)和序列(Series)。
圖片
優勢:Pandera可以在數據處理前捕獲數據錯誤,工作方式類似于Pydantic,但專為Pandas設計,并且支持對數據進行單元測試!
文檔:https://pandera.readthedocs.io/en/stable/
安裝:
pip install pandera
示例:
import pandas as pd
import pandera as pa
# 待驗證的數據
df = pd.DataFrame({
"column1": [1, 4, 0, 10, 9],
"column2": [-1.3, -1.4, -2.9, -10.1, -20.4],
"column3": ["value_1", "value_2", "value_3", "value_2", "value_1"],
})
# 定義模式
schema = pa.DataFrameSchema({
"column1": pa.Column(int, checks=pa.Check.le(10)),
"column2": pa.Column(float, checks=pa.Check.lt(-1.2)),
"column3": pa.Column(str, checks=[
pa.Check.str_startswith("value_"),
# 定義自定義檢查函數,該函數接受一個序列作為輸入,并輸出布爾值或布爾序列
pa.Check(lambda s: s.str.split("_", expand=True).shape[1] == 2)
]),
})
validated_df = schema(df)
print(validated_df)
輸出結果:
column1 column2 column3
0 1 -1.3 value_1
1 4 -1.4 value_2
2 0 -2.9 value_3
3 10 -10.1 value_2
4 9 -20.4 value_1
5.Textual——用Python構建終端用戶界面應用程序
Textual允許開發者使用豐富的組件,用Python構建現代化的終端用戶界面(TUI)應用程序。
優勢:用于創建美觀的終端應用程序,可與Rich庫配合進行樣式設置,無需前端開發經驗。
文檔:https://textual.textualize.io/tutorial/
安裝:
pip install textual
示例:創建TUI應用程序的簡單示例。
from textual.app import App, ComposeResult
from textual.widgets import Label, Button
class QuestionApp(App[str]):
def compose(self) -> ComposeResult:
yield Label("Do you love Textual?")
yield Button("Yes", id="yes", variant="primary")
yield Button("No", id="no", variant="error")
def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(event.button.id)
if __name__ == "__main__":
app = QuestionApp()
reply = app.run()
print(reply)
運行此應用程序將得到以下結果:
圖片
6.LlamaIndex——構建定制AI助手
LlamaIndex簡化了為基于大語言模型(LLM)的應用程序對大型數據集進行索引和查詢的過程。
優勢:LlamaIndex用于檢索增強生成(RAG),可與OpenAI的GPT模型協同工作,并且能夠處理結構化和非結構化數據。
文檔:https://docs.llamaindex.ai/en/stable/#getting-started
安裝:
pip install llama-index
示例:讓我們從一個簡單示例開始,使用一個可以通過調用工具進行基本乘法運算的智能體。創建名為starter.py
的文件:
- 設置一個名為
OPENAI_API_KEY
的環境變量,并賦予其OpenAI API密鑰。
import asyncio
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.llms.openai import OpenAI
# 定義一個簡單的計算器工具
def multiply(a: float, b: float) -> float:
"""用于將兩個數相乘。"""
return a * b
# 使用我們的計算器工具創建一個智能體工作流
agent = AgentWorkflow.from_tools_or_functions(
[multiply],
llm=OpenAI(model="gpt-4o-mini"),
system_prompt="You are a helpful assistant that can multiply two numbers.",
)
asyncdef main():
# 運行智能體
response = await agent.run("What is 1234 * 4567?")
print(str(response))
# 運行智能體
if __name__ == "__main__":
asyncio.run(main())
運算結果:1234×4567的結果是5,678,678。
7.Robyn——最快的Python Web框架
Robyn是Flask和FastAPI的高性能替代框架,針對多核處理進行了優化。
圖片
優勢: Robyn比FastAPI快5倍。支持異步和多線程,并且借助Rust提升速度。
文檔:https://robyn.tech/documentation/en
安裝:
pip install robyn
示例:使用以下命令創建一個簡單的項目:
$ python -m robyn --create
產生以下輸出:
$ python3 -m robyn --create
? Directory Path:.
? Need Docker? (Y/N) Y
? Please select project type (Mongo/Postgres/Sqlalchemy/Prisma):
? No DB
Sqlite
Postgres
MongoDB
SqlAlchemy
Prisma
這會創建一個具有以下結構的新應用程序:
├── src
│ ├── app.py
├── Dockerfile
現在你可以在app.py
文件中編寫代碼:
from robyn import Request
@app.get("/")
async def h(request: Request) -> str:
return "Hello, world"
可以使用以下命令運行服務器:
python -m robyn app.py
8.DuckDB——閃電般快速的內存數據庫
DuckDB是一個內存中的SQL數據庫,在分析方面比SQLite更快。
圖片
優勢:在分析方面速度極快,無需服務器即可運行,并且能輕松與Pandas和Polars集成。
文檔:https://duckdb.org/docs/stable/clients/python/overview.html
安裝:
pip install duckdb --upgrade
示例:使用pandas數據幀的簡單示例:
import duckdb
import pandas as pd
pandas_df = pd.DataFrame({"a": [42]})
duckdb.sql("SELECT * FROM pandas_df")
輸出結果:
┌───────┐
│ a │
│ int64 │
├───────┤
│ 42 │
└───────┘
9.Django——全棧Web框架
Django是高級Python Web框架,用于快速構建安全、可擴展的應用程序。
圖片
優勢:Django內置對象關系映射(ORM)、包含身份驗證系統、具有可擴展性和安全性,還有更多優勢。
文檔:https://docs.djangoproject.com/en/5.2/
安裝:
pip install django
示例:創建一個新的Django項目:
django-admin startproject myproject
cd myproject
python manage.py runserver
你應該會看到應用程序在http:127.0.0.1:8000/
上運行。
10.FastAPI——高性能API框架
FastAPI是個輕量級且快速的Python Web框架,用于構建支持異步的RESTful API。
圖片
優勢:內置異步支持、自動生成OpenAPI和Swagger UI,并且速度快(基于Starlette和Pydantic構建)。
文檔:https://fastapi.tiangolo.com/learn/
安裝:
pip install fastapi uvicorn
示例:使用FastAPI創建API的簡單示例:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
運行服務器:
uvicorn main:app --reload
你應該會看到應用程序在http:127.0.0.1:8000/
上運行。
11.LangChain——人工智能驅動的應用框架
LangChain是Python框架,簡化了與像OpenAI的GPT這樣的大語言模型(LLM)的協作過程。
優勢:LangChain可以與OpenAI、Hugging Face等集成,將多個大語言模型調用鏈接在一起,并且支持基于記憶和檢索的查詢。
文檔:https://python.langchain.com/docs/introduction/
安裝:
pip install langchain
示例:使用OpenAI模型創建聊天機器人的簡單示例:
pip install -qU "langchain[openai]"
import getpass
import os
from langchain.chat_models import init_chat_model
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
model = init_chat_model("gpt-4o-mini", model_provider="openai")
model.invoke("Hello, world!")
你會看到聊天機器人的回復。
12.Pydantic——數據驗證與解析
Pydantic通過Python類型提示實現數據驗證,在FastAPI中有著廣泛應用。
圖片
優勢:Pydantic具備自動數據驗證功能,基于類型提示進行數據解析,與FastAPI搭配使用效果極佳。
文檔:https://docs.pydantic.dev/latest/
安裝:
pip install pydantic
示例:
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
user = User(name="Aashish Kumar", age=25)
print(user) # User(name='Aashish Kumar', age=25)
print(user.name) # 'Aashish Kumar'
print(user.age) # 25
13.Flet——用Python構建Web、移動和桌面UI
Flet僅使用Python就能構建現代化的Web、桌面和移動應用(無需HTML/CSS/JS )。
圖片
優勢:無需掌握JavaScript或前端知識,可在Web、Windows、macOS和Linux等平臺使用,是一款響應式UI框架。
文檔:https://flet.dev/docs/
安裝:
pip install flet
示例:構建一個簡單的計數器應用:
import flet
from flet import IconButton, Page, Row, TextField, icons
def main(page: Page):
page.title = "Flet counter example"
page.vertical_alignment = "center"
txt_number = TextField(value="0", text_align="right", width=100)
def minus_click(e):
txt_number.value = str(int(txt_number.value) - 1)
page.update()
def plus_click(e):
txt_number.value = str(int(txt_number.value) + 1)
page.update()
page.add(
Row(
[
IconButton(icons.REMOVE, on_click=minus_click),
txt_number,
IconButton(icons.ADD, on_click=plus_click),
],
alignment="center",
)
)
flet.app(target=main)
運行程序:
python counter.py
應用程序將在原生操作系統窗口中啟動,這是替代Electron的不錯選擇。
圖片
如果想將應用作為Web應用運行,只需將最后一行代碼替換為:
flet.app(target=main, view=flet.AppView.WEB_BROWSER)
再次運行,即可立即獲得Web應用:
圖片
14.Weaviate——用于AI與搜索的向量數據庫
Weaviate是一款快速的開源向量數據庫,適用于語義搜索和AI應用。
圖片
優勢:是人工智能驅動搜索的理想選擇,可存儲文本、圖像和嵌入向量,能應對大規模數據集的需求。
文檔:https://weaviate.io/developers/weaviate
安裝:
pip install -U weaviate-client
示例:使用Docker以默認設置運行Weaviate,在終端中運行以下命令:
docker run -p 8080:8080 -p 50051:50051 cr.weaviate.io/semitechnologies/weaviate:1.29.0
Docker實例默認運行在http://localhost:8080
。
若要連接到本地實例且無需身份驗證:
import weaviate
client = weaviate.connect_to_local()
print(client.is_ready())
15.Reflex——用Python構建Web應用(前端+后端)
Reflex是一個全棧Web框架,用于使用Python構建現代化Web應用,與Streamlit類似,但可定制性更強。
圖片
優勢:可以用Python構建類似React的用戶界面,具備狀態管理功能,前后端代碼集成在一處。
文檔:https://reflex.dev/docs/getting-started/introduction/
安裝:
pip install reflex
示例:使用以下命令創建一個Reflex項目:
mkdir my_app_name
cd my_app_name
reflex init
創建簡單應用:
# app.py
import reflex as rx
import openai
openai_client = openai.OpenAI()
# 后端代碼
class State(rx.State):
"""應用程序狀態。"""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""根據提示獲取圖片。"""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
# 前端代碼
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# 將狀態和頁面添加到應用程序
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
運行開發服務器:
reflex run
你會看到應用在http://localhost:3000
運行。
None