一、使用numpy和matplotlib进行绘制图表

import numpy as np

from matplotlib import pyplot as plt

# 局部处理中文乱码

# 适合小批量的绘图场景

# plt.rcParams['font.sans-serif']=['SimHei']

# plt.rcParams['axes.unicode_minus']=False

# 全局处理中文乱码

# 打印matplotlibrc文件的路径

# import matplotlib

# print(matplotlib.matplotlib_fname())

# 第一种绘图方式

# 最基本最简单的方式:直接使用plot()绘图

def test01():

    x = np.linspace(-6, 6, 100)

    y1 = np.sin(x)

    y2 = np.cos(x)

    # plot():绘制曲线函数

    plt.plot(x, y1, 'b')

    plt.plot(x, y2, 'r')

    # 显示图形方法

    plt.show()

# 第二种方式:创建自定义画布,在画布中创建绘图区域,在绘图区域绘制图形

def test02():

    x = np.linspace(-6, 6, 100)

    y = x ** 2

    y2 = np.tan(x)

    # 创建画布

    fig = plt.figure(figsize=(12, 10))

    # 创建绘图区域

    # add_axes参数:数组[left,bottom,width,height],数组元素的取值范围:(0,1)

    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

    # 在plot方法上添加label

    # 通过plt.legend()添加图例

    ax.plot(x, y, label='x^2函数')

    ax.plot(x, y2, label='tan函数')

    # 图例设置

    ax.legend()

    plt.show()

# 第三种方法:将画布分割为多个子绘图区域

def test03():

    x = np.linspace(-6, 6, 100)

    y1 = np.sin(x)

    y2 = np.cos(x)

    y3 = np.tan(x)

    # 创建画布

    fig = plt.figure()

    # add_subplot(row,col,index)

    # row:画布行数

    # col:画布列数

    # index:子绘图区域的编号

    # 子绘图区域的index不能超过row*col的值

    ax = fig.add_subplot(2, 3, 1)

    ax.plot(x, y1, label='sin')

    ax = fig.add_subplot(2, 3, 2)

    ax.plot(x, y2, label='cos')

    ax = fig.add_subplot(2, 3, 3)

    ax.plot(x, y3, label='tan')

    ax = fig.add_subplot(2, 3, 4)

    ax.plot(x, y3, label='tan')

    ax.legend()

    plt.show()
 

# 第四种绘图方法:subplots()

def test04():

    x = np.linspace(-6, 6, 100)

    y1 = np.sin(x)

    y2 = np.cos(x)

    y3 = np.tan(x)

    # subplots(rows,cols)创建多个子绘图区域

    # rows:画布行数

    # cols:画布列数

    # 返回的对象:fig画布对象,axs子绘图区域对象,该对象是一个数组

    # 创建的子图区域(1,3)是一维数组

    # fig, axs = plt.subplots(1, 3)

    # axs[0].plot(x, y1, label='sin')

    # axs[0].legend()

    #

    # axs[1].plot(x, y2, label='cos')

    # axs[1].legend()

    #

    # axs[2].plot(x, y3, label='tan')

    # axs[2].legend()

    #

    # plt.show()

    # 创建二维的子图区域数组

    # 子图区域数组的下标不能超出rows和cols的范围

    fig, axs = plt.subplots(2, 3)

    axs[0, 0].plot(x, y1, label='sin')

    axs[0, 1].plot(x, y2, label='cos')

    axs[1, 1].plot(x, y3, label='tan')

    plt.show()


 

if __name__ == '__main__':

    # test01()

    # test02()

    # test03()

    test04()

二、数组操作

NumPy(Numerical Python)是Python中用于科学计算的核心库,提供了高效的多维数组(`ndarray`)操作。以下是NumPy数组的常见操作分类和示例:

1. 创建数组
从列表/元组创建 
  import numpy as np
  a = np.array([1, 2, 3])          # 一维数组
  b = np.array([[1, 2], [3, 4]])   # 二维数组

初始化特殊数组

  np.zeros((2, 3))     # 全0数组
  np.ones((2, 2))      # 全1数组
  np.empty((3, 3))     # 未初始化的数组
  np.eye(3)            # 单位矩阵
  np.arange(0, 10, 2)  # 类似range的序列
  np.linspace(0, 1, 5) # 等差序列
  np.random.rand(2, 2) # 随机数组(0~1)
 

2. 数组属性
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr.shape      # 形状 (2, 3)
arr.ndim       # 维度 2
arr.size       # 元素总数 6
arr.dtype      # 数据类型 int64

3. 数组索引与切片

基本索引
  arr = np.array([1, 2, 3, 4])
  arr[0]       # 1
  arr[1:3]     # array([2, 3])
 

多维数组索引
  arr_2d = np.array([[1, 2], [3, 4]])
  arr_2d[0, 1]     # 2 (第0行第1列)
  arr_2d[:, 1]     # 所有行的第1列 ([2, 4])
 

布尔索引
  arr = np.array([1, 2, 3, 4])
  arr[arr > 2]     # array([3, 4])
 

4. 数组形状操作
arr = np.arange(6)
arr.reshape(2, 3)  # 改为2x3形状
arr.flatten()      # 展平为一维
arr.T              # 转置
np.transpose(arr)  # 转置(高维通用)

5. 数组运算
算术运算(逐元素)  
  a = np.array([1, 2])
  b = np.array([3, 4])
  a + b    # array([4, 6])
  a * b    # array([3, 8])

广播机制(形状扩展)  
  a = np.array([1, 2])
  a + 5    # array([6, 7]) (标量广播)
 

矩阵乘法
  a @ b.T           # 点积
  np.dot(a, b.T)    # 同上
 

通用函数(ufunc)
  np.sqrt(a)       # 开平方
  np.exp(a)        # 指数
  np.sin(a)        # 三角函数

6. 统计与聚合
arr = np.array([[1, 2], [3, 4]])
arr.sum()          # 所有元素和 10
arr.sum(axis=0)    # 沿列的求和 ([4, 6])
arr.mean()         # 平均值 2.5
arr.max(axis=1)    # 每行的最大值 [2, 4]
np.median(arr)     # 中位数 2.5

7. 数组拼接与分割
拼接
  a = np.array([1, 2])
  b = np.array([3, 4])
  np.concatenate([a, b])        # [1, 2, 3, 4]
  np.vstack([a, b])             # 垂直堆叠
  np.hstack([a, b])             # 水平堆叠

分割
  arr = np.arange(6)
  np.split(arr, 2)              # 均等分割
  np.array_split(arr, 3)        # 不等分割

8. 排序与去重
arr = np.array([3, 1, 2])
arr.sort()              # 原地排序 [1, 2, 3]
np.unique(arr)          # 去重并排序

9. 文件IO
np.save('data.npy', arr)    # 保存为二进制文件
np.load('data.npy')         # 加载
np.savetxt('data.txt', arr) # 保存为文本

10. 其他高级操作
向量化计算(避免循环)  
  arr = np.array([1, 2, 3])
  arr * 2  # 直接广播计算

条件逻辑
  np.where(arr > 2, 1, 0)  # 条件替换

线性代数 
  np.linalg.inv(A)     # 矩阵求逆
  np.linalg.eig(A)     # 特征值分解

三、pandas库

1.1)series创建

import pandas as pd

import numpy as np

# 创建空Series对象

s = pd.Series()

print(s)

# 通过python列表创建

s = pd.Series([1, 2, 3, 4, 5])

print(s)

# ndarray创建Series

s = pd.Series(np.array([1, 2, 3, 4, 5]))

print(s)

# 字典创建Series,字典中的key是Series的标签名,value是Series的元素值

dic = {"id": 1, "age": 20, "name": "zhangsan"}

s = pd.Series(dic)

print(s)

1.2)series遍历

import pandas as pd

# 访问Series的元素

s = pd.Series([1, 2, 3, 4, 5, 6])

print(s[3])

# 使用下标做切片时,终止值不被包含

print(s[:2])

s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])

print(s)

print(s['d'])

# 使用标签做切片时,终止值被包含

print(s['a':'c'])

# 遍历

# 1.使用index遍历

s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])

# index:获取标签

for idx in s.index:

    print(idx, s[idx])

# 2.使用values遍历

s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])

for v in s.values:

    print(v)

# 3.使用items()遍历 ,返回index和value

s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])

for idx, val in s.items():

    print(idx, val)

2.1)dataframe操作

1. 创建 DataFrame

import pandas as pd
import numpy as np

# 从字典创建
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)

# 从列表创建
data = [['Alice', 25, 'New York'], 
        ['Bob', 30, 'Paris'], 
        ['Charlie', 35, 'London']]
df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])

# 从Numpy数组创建
arr = np.random.rand(3, 3)
df = pd.DataFrame(arr, columns=['A', 'B', 'C'])

# 从CSV文件创建
df = pd.read_csv('data.csv')

2. 查看和检查数据

# 查看前n行
df.head(2)

# 查看后n行
df.tail(2)

# 查看DataFrame信息
df.info()

# 查看统计摘要
df.describe()

# 查看形状
df.shape

# 查看列名
df.columns

# 查看索引
df.index

# 查看数据类型
df.dtypes

3. 选择数据

选择列
# 选择单列
df['Name']

# 选择多列
df[['Name', 'Age']]

# 使用点表示法(列名不含空格时)
df.Name

选择行
# 通过索引标签
df.loc[0]  # 第一行

# 通过位置索引
df.iloc[0]  # 第一行

# 切片选择多行
df[0:2]  # 前两行

# 通过条件选择
df[df['Age'] > 30]

选择行和列
# 选择特定行和列
df.loc[0:1, ['Name', 'City']]

# 使用iloc按位置选择
df.iloc[0:2, 0:2]

4. 数据筛选

# 单条件筛选
df[df['Age'] > 25]

# 多条件筛选
df[(df['Age'] > 25) & (df['City'] == 'Paris')]

# 使用isin筛选
df[df['City'].isin(['New York', 'London'])]

# 使用query方法
df.query('Age > 25 and City == "Paris"')

5. 数据排序
# 按单列排序
df.sort_values('Age')

# 按多列排序
df.sort_values(['City', 'Age'])

# 降序排序
df.sort_values('Age', ascending=False)

# 按索引排序
df.sort_index()

 6. 添加/删除数据

添加列
# 添加新列
df['Salary'] = [50000, 60000, 70000]

# 基于现有列计算新列
df['Age_plus_10'] = df['Age'] + 10

# 使用assign方法(返回新DataFrame)
df = df.assign(Double_Age = lambda x: x['Age'] * 2)

添加行
# 使用append(不推荐,未来会移除)
df = df.append({'Name': 'David', 'Age': 40, 'City': 'Berlin'}, ignore_index=True)

# 更好的方式:使用concat
new_row = pd.DataFrame({'Name': ['David'], 'Age': [40], 'City': ['Berlin']})
df = pd.concat([df, new_row], ignore_index=True)

删除数据
# 删除列
df.drop('Age_plus_10', axis=1, inplace=True)

# 删除多列
df.drop(['Double_Age', 'Salary'], axis=1, inplace=True)

# 删除行
df.drop(0, axis=0, inplace=True)  # 删除第一行

# 删除满足条件的行
df.drop(df[df['Age'] < 30].index, inplace=True)

7. 处理缺失值
# 创建含缺失值的DataFrame
df = pd.DataFrame({'A': [1, 2, np.nan], 'B': [5, np.nan, np.nan], 'C': [1, 2, 3]})

# 检查缺失值
df.isna()
df.isnull().sum()

# 删除含缺失值的行
df.dropna()

# 填充缺失值
df.fillna(value=0)
df['A'].fillna(df['A'].mean(), inplace=True)

# 向前填充
df.fillna(method='ffill')

# 向后填充
df.fillna(method='bfill')

8. 数据分组和聚合

# 分组统计
df.groupby('City')['Age'].mean()

# 多列分组
df.groupby(['City', 'Name']).size()

# 多种聚合函数
df.groupby('City').agg({'Age': ['mean', 'min', 'max'], 'Name': 'count'})

# 使用pivot_table
pd.pivot_table(df, values='Age', index='City', aggfunc=np.mean)

9. 数据合并

# 创建两个DataFrame
df1 = pd.DataFrame({'key': ['A', 'B', 'C'], 'value': [1, 2, 3]})
df2 = pd.DataFrame({'key': ['A', 'B', 'D'], 'value': [4, 5, 6]})

# 内连接
pd.merge(df1, df2, on='key', how='inner')

# 左连接
pd.merge(df1, df2, on='key', how='left')

# 外连接
pd.merge(df1, df2, on='key', how='outer')

# 纵向合并
pd.concat([df1, df2], axis=0)

10. 数据转换

# 重命名列
df.rename(columns={'Name': 'Full Name', 'Age': 'Years'}, inplace=True)

# 替换值
df['City'].replace({'New York': 'NY', 'Paris': 'FR'}, inplace=True)

# 应用函数
df['Name'].apply(lambda x: x.upper())

# 使用map映射
df['City_Code'] = df['City'].map({'New York': 'NY', 'Paris': 'FR', 'London': 'LDN'})

# 分类数据
df['Age_Group'] = pd.cut(df['Age'], bins=[20, 30, 40], labels=['20-30', '30-40'])

11. 时间序列处理
# 创建时间序列DataFrame
dates = pd.date_range('20230101', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))

# 选择特定时间范围
df['2023-01-01':'2023-01-03']

# 重采样
df.resample('M').mean()

# 移动窗口计算
df.rolling(window=2).mean()

12. 输入输出
# 保存到CSV
df.to_csv('output.csv', index=False)

# 从Excel读取
df = pd.read_excel('data.xlsx')

# 保存到Excel
df.to_excel('output.xlsx', sheet_name='Sheet1')

# 从SQL数据库读取
import sqlite3
conn = sqlite3.connect('database.db')
df = pd.read_sql('SELECT * FROM table_name', conn)

13. 性能优化技巧
# 使用向量化操作代替循环
df['New_Col'] = df['Col1'] + df['Col2']

# 使用eval进行表达式计算
df.eval('New_Col = Col1 + Col2', inplace=True)

# 使用category类型减少内存
df['City'] = df['City'].astype('category')

# 使用query提高筛选性能
df.query('Age > 25 & City == "Paris"')


 

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐