欢迎访问宙启技术站
智能推送

Python函数库:常用的Python函数及其用法

发布时间:2023-07-06 09:04:17

Python函数库是指Python程序员常用的一些函数集合,这些函数可以有效地帮助开发者快速完成任务,提高开发效率。下面将介绍一些常用的Python函数库及其用法。

1. NumPy:NumPy 是Python语言的一个很重要的数值计算库,用于构建数据结构和执行高性能数值计算任务。

示例用法:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)  # 输出 [1 2 3 4 5]

arr_mean = np.mean(arr)
print(arr_mean)  # 输出 3.0

2. Pandas:Pandas是一个用于数据操作和分析的库,提供了高效的数据结构和数据分析工具。

示例用法:

import pandas as pd

data = {'Name': ['Tom', 'Jerry', 'Spike', 'Tyke'],
        'Age': [25, 30, 35, 5],
        'Country': ['USA', 'UK', 'USA', 'USA']}

df = pd.DataFrame(data)
print(df)  # 输出一个表格形式的数据

df_mean_age = df['Age'].mean()
print(df_mean_age)  # 输出平均年龄

3. Matplotlib:Matplotlib是一个用于绘制数据图表的库,可以创建多种类型的图形,包括折线图、柱状图、散点图等。

示例用法:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Line Chart')
plt.show()

4. Requests:Requests 是Python中一个用户友好的HTTP库,用于发送 HTTP 请求并处理响应。

示例用法:

import requests

response = requests.get('https://www.example.com')
print(response.text)  # 输出网页的内容

response_status_code = response.status_code
print(response_status_code)  # 输出响应的状态码

5. BeautifulSoup:BeautifulSoup是一个用于解析HTML和XML文档的库,能够从中提取有用的数据。

示例用法:

from bs4 import BeautifulSoup

html = '''
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
'''

soup = BeautifulSoup(html, 'html.parser')
h1_text = soup.find('h1').text
print(h1_text)  # 输出 Hello, World!

6. SQLAlchemy:SQLAlchemy是一个Python ORM(对象关系映射)库,用于管理数据库操作。

示例用法:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

engine = create_engine('sqlite:///database.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

user = User(name='Tom', age=25)
session.add(user)
session.commit()

users = session.query(User).all()
for user in users:
    print(user.name, user.age)

以上是介绍常用的Python函数库及其用法的简要说明。这些函数库在Python开发中非常有用,可以让开发者更加高效地完成各种任务。