2025 最新出爐!15 個 Python 庫帶你飛
在Python的技術(shù)生態(tài)中,豐富多樣的庫是其一大亮點,這些出色的庫大大拓展了Python的應(yīng)用邊界,堪稱改變編程格局的“利器”。當(dāng)下,技術(shù)迭代日新月異,若想在2025年的編程領(lǐng)域中搶占先機,有幾款極具變革性的現(xiàn)代庫不容錯過。
1.Polars——極速數(shù)據(jù)幀庫
Polars是用Rust編寫的超快速數(shù)據(jù)幀庫,用于處理結(jié)構(gòu)化數(shù)據(jù)。
圖片
優(yōu)勢:Polars比Pandas快10到100倍。支持對大型數(shù)據(jù)集進行延遲求值,并且能與Apache Arrow原生協(xié)作。
文檔:https://docs.pola.rs/
安裝:
pip install polars示例:以下是使用Polars創(chuàng)建數(shù)據(jù)幀的簡單示例:
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)輸出結(jié)果:
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 語言編寫的超快速代碼檢查工具,其設(shè)計初衷便是憑借自身強大功能,以 “一器之力” 取代 Flake8、Black 和 isort 這幾款傳統(tǒng)工具,為開發(fā)者提供更高效、便捷的代碼檢查與格式化解決方案 。
圖片
優(yōu)勢:它比Flake8快20倍,支持自動修復(fù)問題,兼具格式化和代碼檢查功能。
文檔:https://docs.astral.sh/ruff/
安裝:
pip install ruff示例:我們可以使用uv初始化一個項目:
uv init --lib demo這條命令會創(chuàng)建一個具有以下結(jié)構(gòu)的Python項目:
demo
├── README.md
├── pyproject.toml
└── src
    └── demo
        ├── __init__.py
        └── py.typed然后,將src/demo/__init__.py的內(nèi)容替換為以下代碼:
from typing import Iterable
import os
def sum_even_numbers(numbers: Iterable[int]) -> int:
    """給定一個整數(shù)的可迭代對象,返回其中所有偶數(shù)的和。"""
    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讓開發(fā)者可以在瀏覽器中編寫和執(zhí)行Python代碼,類似于JavaScript。
優(yōu)勢:PyScript支持開發(fā)基于Python的網(wǎng)頁應(yīng)用,可直接在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>示例:創(chuàng)建一個簡單的.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>
    <!-- 現(xiàn)在可以使用<py-script>標簽在其中編寫Python代碼 -->
    <py-script>
        import sys
        from pyscript import display
        display(sys.version)
    </py-script>
</body>
</html>4.Pandera——用于Pandas的數(shù)據(jù)驗證工具
Pandera通過基于模式的驗證方式,幫助驗證Pandas的數(shù)據(jù)幀(DataFrames)和序列(Series)。
圖片
優(yōu)勢:Pandera可以在數(shù)據(jù)處理前捕獲數(shù)據(jù)錯誤,工作方式類似于Pydantic,但專為Pandas設(shè)計,并且支持對數(shù)據(jù)進行單元測試!
文檔:https://pandera.readthedocs.io/en/stable/
安裝:
pip install pandera示例:
import pandas as pd
import pandera as pa
# 待驗證的數(shù)據(jù)
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_"),
        # 定義自定義檢查函數(shù),該函數(shù)接受一個序列作為輸入,并輸出布爾值或布爾序列
        pa.Check(lambda s: s.str.split("_", expand=True).shape[1] == 2)
    ]),
})
validated_df = schema(df)
print(validated_df)輸出結(jié)果:
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_15.Textual——用Python構(gòu)建終端用戶界面應(yīng)用程序
Textual允許開發(fā)者使用豐富的組件,用Python構(gòu)建現(xiàn)代化的終端用戶界面(TUI)應(yīng)用程序。
優(yōu)勢:用于創(chuàng)建美觀的終端應(yīng)用程序,可與Rich庫配合進行樣式設(shè)置,無需前端開發(fā)經(jīng)驗。
文檔:https://textual.textualize.io/tutorial/
安裝:
pip install textual示例:創(chuàng)建TUI應(yīng)用程序的簡單示例。
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)運行此應(yīng)用程序?qū)⒌玫揭韵陆Y(jié)果:
圖片
6.LlamaIndex——構(gòu)建定制AI助手
LlamaIndex簡化了為基于大語言模型(LLM)的應(yīng)用程序?qū)Υ笮蛿?shù)據(jù)集進行索引和查詢的過程。
優(yōu)勢:LlamaIndex用于檢索增強生成(RAG),可與OpenAI的GPT模型協(xié)同工作,并且能夠處理結(jié)構(gòu)化和非結(jié)構(gòu)化數(shù)據(jù)。
文檔:https://docs.llamaindex.ai/en/stable/#getting-started
安裝:
pip install llama-index示例:讓我們從一個簡單示例開始,使用一個可以通過調(diào)用工具進行基本乘法運算的智能體。創(chuàng)建名為starter.py的文件:
- 設(shè)置一個名為
OPENAI_API_KEY的環(huán)境變量,并賦予其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:
    """用于將兩個數(shù)相乘。"""
    return a * b
# 使用我們的計算器工具創(chuàng)建一個智能體工作流
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())運算結(jié)果:1234×4567的結(jié)果是5,678,678。
7.Robyn——最快的Python Web框架
Robyn是Flask和FastAPI的高性能替代框架,針對多核處理進行了優(yōu)化。
圖片
優(yōu)勢: Robyn比FastAPI快5倍。支持異步和多線程,并且借助Rust提升速度。
文檔:https://robyn.tech/documentation/en
安裝:
pip install robyn示例:使用以下命令創(chuàng)建一個簡單的項目:
$ python -m robyn --create產(chǎn)生以下輸出:
$ 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這會創(chuàng)建一個具有以下結(jié)構(gòu)的新應(yīng)用程序:
├── src
│   ├── app.py
├── Dockerfile現(xiàn)在你可以在app.py文件中編寫代碼:
from robyn import Request
@app.get("/")
async def h(request: Request) -> str:
    return "Hello, world"可以使用以下命令運行服務(wù)器:
python -m robyn app.py8.DuckDB——閃電般快速的內(nèi)存數(shù)據(jù)庫
DuckDB是一個內(nèi)存中的SQL數(shù)據(jù)庫,在分析方面比SQLite更快。
圖片
優(yōu)勢:在分析方面速度極快,無需服務(wù)器即可運行,并且能輕松與Pandas和Polars集成。
文檔:https://duckdb.org/docs/stable/clients/python/overview.html
安裝:
pip install duckdb --upgrade示例:使用pandas數(shù)據(jù)幀的簡單示例:
import duckdb
import pandas as pd
pandas_df = pd.DataFrame({"a": [42]})
duckdb.sql("SELECT * FROM pandas_df")輸出結(jié)果:
┌───────┐
│   a   │
│ int64 │
├───────┤
│    42 │
└───────┘9.Django——全棧Web框架
Django是高級Python Web框架,用于快速構(gòu)建安全、可擴展的應(yīng)用程序。
圖片
優(yōu)勢:Django內(nèi)置對象關(guān)系映射(ORM)、包含身份驗證系統(tǒng)、具有可擴展性和安全性,還有更多優(yōu)勢。
文檔:https://docs.djangoproject.com/en/5.2/
安裝:
pip install django示例:創(chuàng)建一個新的Django項目:
django-admin startproject myproject
cd myproject
python manage.py runserver你應(yīng)該會看到應(yīng)用程序在http:127.0.0.1:8000/上運行。
10.FastAPI——高性能API框架
FastAPI是個輕量級且快速的Python Web框架,用于構(gòu)建支持異步的RESTful API。
圖片
優(yōu)勢:內(nèi)置異步支持、自動生成OpenAPI和Swagger UI,并且速度快(基于Starlette和Pydantic構(gòu)建)。
文檔:https://fastapi.tiangolo.com/learn/
安裝:
pip install fastapi uvicorn示例:使用FastAPI創(chuàng)建API的簡單示例:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}運行服務(wù)器:
uvicorn main:app --reload你應(yīng)該會看到應(yīng)用程序在http:127.0.0.1:8000/上運行。
11.LangChain——人工智能驅(qū)動的應(yīng)用框架
LangChain是Python框架,簡化了與像OpenAI的GPT這樣的大語言模型(LLM)的協(xié)作過程。

優(yōu)勢:LangChain可以與OpenAI、Hugging Face等集成,將多個大語言模型調(diào)用鏈接在一起,并且支持基于記憶和檢索的查詢。
文檔:https://python.langchain.com/docs/introduction/
安裝:
pip install langchain示例:使用OpenAI模型創(chuàng)建聊天機器人的簡單示例:
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!")你會看到聊天機器人的回復(fù)。
12.Pydantic——數(shù)據(jù)驗證與解析
Pydantic通過Python類型提示實現(xiàn)數(shù)據(jù)驗證,在FastAPI中有著廣泛應(yīng)用。
圖片
優(yōu)勢:Pydantic具備自動數(shù)據(jù)驗證功能,基于類型提示進行數(shù)據(jù)解析,與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)  # 2513.Flet——用Python構(gòu)建Web、移動和桌面UI
Flet僅使用Python就能構(gòu)建現(xiàn)代化的Web、桌面和移動應(yīng)用(無需HTML/CSS/JS )。
圖片
優(yōu)勢:無需掌握JavaScript或前端知識,可在Web、Windows、macOS和Linux等平臺使用,是一款響應(yīng)式UI框架。
文檔:https://flet.dev/docs/
安裝:
pip install flet示例:構(gòu)建一個簡單的計數(shù)器應(yīng)用:
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應(yīng)用程序?qū)⒃谠僮飨到y(tǒng)窗口中啟動,這是替代Electron的不錯選擇。
圖片
如果想將應(yīng)用作為Web應(yīng)用運行,只需將最后一行代碼替換為:
flet.app(target=main, view=flet.AppView.WEB_BROWSER)再次運行,即可立即獲得Web應(yīng)用:
圖片
14.Weaviate——用于AI與搜索的向量數(shù)據(jù)庫
Weaviate是一款快速的開源向量數(shù)據(jù)庫,適用于語義搜索和AI應(yīng)用。
圖片
優(yōu)勢:是人工智能驅(qū)動搜索的理想選擇,可存儲文本、圖像和嵌入向量,能應(yīng)對大規(guī)模數(shù)據(jù)集的需求。
文檔:https://weaviate.io/developers/weaviate
安裝:
pip install -U weaviate-client示例:使用Docker以默認設(shè)置運行Weaviate,在終端中運行以下命令:
docker run -p 8080:8080 -p 50051:50051 cr.weaviate.io/semitechnologies/weaviate:1.29.0Docker實例默認運行在http://localhost:8080。
若要連接到本地實例且無需身份驗證:
import weaviate
client = weaviate.connect_to_local()
print(client.is_ready())15.Reflex——用Python構(gòu)建Web應(yīng)用(前端+后端)
Reflex是一個全棧Web框架,用于使用Python構(gòu)建現(xiàn)代化Web應(yīng)用,與Streamlit類似,但可定制性更強。
圖片
優(yōu)勢:可以用Python構(gòu)建類似React的用戶界面,具備狀態(tài)管理功能,前后端代碼集成在一處。
文檔:https://reflex.dev/docs/getting-started/introduction/
安裝:
pip install reflex示例:使用以下命令創(chuàng)建一個Reflex項目:
mkdir my_app_name
cd my_app_name
reflex init創(chuàng)建簡單應(yīng)用:
# app.py
import reflex as rx
import openai
openai_client = openai.OpenAI()
# 后端代碼
class State(rx.State):
    """應(yīng)用程序狀態(tài)。"""
    prompt = ""
    image_url = ""
    processing = False
    complete = False
    def get_image(self):
        """根據(jù)提示獲取圖片。"""
        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",
    )
# 將狀態(tài)和頁面添加到應(yīng)用程序
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")運行開發(fā)服務(wù)器:
reflex run你會看到應(yīng)用在http://localhost:3000運行。
None















 
 
 













 
 
 
 