pythonpanda库从基础到高级操作分析

作者:

文章目录
  • Pandas 是 Python 数据科学领域的核心库,专为处理结构化数据而设计。它提供了两种核心数据结构:Series(一维数组)和DataFrame(二维表格),支持高效的数据操作、清洗和分析。Pandas 的主要优势包括: 高效处理大型数据集 灵活的数据清洗和转换功能 强大的分组和聚合操作 无缝对接其他科学计算库(如 NumPy、Matplotlib) import pandas as pd import numpy as np # 创建Series(一维数据结构) s = pd.Series([1, 3, 5, np.nan, 6, 8]) print(“Series示例:”) print(s) # 创建DataFrame(二维表格) df = pd.DataFrame({ ‘Name’: [‘Alice’, ‘Bob’, ‘Charlie’], ‘Age’: [25, 30, 35], ‘City’: [‘New York’, ‘London’, ‘Paris’] }) print(“nDataFrame示例:”) print(df) 输出结果: Series示例:0     1.01     3.02     5.03     NaN4     6.05     8.0dtype: float64 DataFrame示例:     Name  Age      City0   Alice   25  New York1     Bob   30    London2  Charlie   35     Paris
  • Pandas 提供了丰富的接口用于读取不同格式的数据,并支持便捷的数据探查功能。 # 构造示例数据 data = { ‘Name’: [‘Alice’, ‘Bob’, ‘Charlie’, ‘David’, ‘Eve’], ‘Age’: [25, 30, 35, 28, 22], ‘City’: [‘New York’, ‘London’, ‘Paris’, ‘New York’, ‘Berlin’], ‘Salary’: [5000, 6000, 7000, 5500, 4500] } df = pd.DataFrame(data) # 保存为CSV文件 df.to_csv(‘sample_data.csv’, index=False) # 从CSV读取数据 df = pd.read_csv(‘sample_data.csv’) # 查看数据基本信息 print(“数据基本信息:”) df.info() # 查看数据前几行 print(“n数据前5行:”) print(df.head()) # 查看数据统计摘要 print(“n数据统计摘要:”) print(df.describe()) # 查看数据形状 rows, columns = df.shape print(f”n数据形状: {rows}行{columns}列”) 输出结果: 数据基本信息:<class 'pandas.core.frameworks.dataframe.DataFrame'>RangeIndex: 5 entries, 0 to 4Data columns (total 4 columns): #   Column  Non-Null Count  Dtype—  ——  ————–  —– 0   Name    5 non-null      object 1   Age     5 non-null      int64 2   City    5 non-null      object 3   Salary  5 non-null      int64dtypes: int64(2), object(2)memory usage: 240.0+ bytes 数据前5行:     Name  Age     City  Salary0   Alice   25  New York    50001     Bob   30   London    60002  Charlie   35    Paris    70003   David   28  New York    55004     Eve   22   Berlin    4500 数据统计摘要:       Age     Salarycount  5.0   5.0mean   28.0  5600.0std     5.0   953.9min    22.0  4500.025%    25.0  5000.050%    28.0  5500.075%    30.0  6000.0max    35.0  7000.0 数据形状: 5行4列
  • Pandas 支持多种索引方式,包括位置索引、标签索引和布尔索引,满足不同场景的数据访问需求。 # 位置索引 (iloc) print(“第一行数据 (iloc[0]):”) print(df.iloc[0]) print(“n前两行数据 (iloc[:2]):”) print(df.iloc[:2]) # 标签索引 (loc) df.set_index(‘Name’, inplace=True) print(“n以Name为索引后,查询Alice的记录 (loc[‘Alice’]):”) print(df.loc[‘Alice’]) # 布尔索引 print(“n年龄大于30的记录:”) print(df[df[‘Age’] > 30]) # 组合索引 print(“n查询New York的高收入人群 (Salary > 5000):”) print(df[(df[‘City’] == ‘New York’) & (df[‘Salary’] > 5000)]) 输出结果: 第一行数据 (iloc[0]):Name         AliceAge            25City      New YorkSalary       5000Name: 0, dtype: object 前两行数据 (iloc[:2]):     Name  Age     City  Salary0   Alice   25  New York    50001     Bob   30   London    6000 以Name为索引后,查询Alice的记录 (loc['Alice']):Age            25City      New YorkSalary       5000Name: Alice, dtype: object 年龄大于30的记录:          Age     City  SalaryName                        Charlie    35    Paris    7000 查询New York的高收入人群 (Salary > 5000):          Age     City  SalaryName                        David      28  New York    5500
  • GroupBy 是 Pandas 中最强大的功能之一,支持按指定列分组后进行各种聚合计算。 # 按City分组,计算平均年龄 city_age_mean = df.groupby(‘City’)[‘Age’].mean() print(“各城市平均年龄:”) print(city_age_mean) # 多列分组并应用多个聚合函数 grouped = df.groupby([‘City’, ‘Age’]).agg({ ‘Salary’: [‘mean’, ‘sum’] }) print(“n按城市和年龄分组后的薪资统计:”) print(grouped) # 分组后筛选 – 只保留平均薪资大于5500的城市 filtered_groups = df.groupby(‘City’).filter(lambda x: x[‘Salary’].mean() > 5500) print(“n平均薪资大于5500的城市记录:”) print(filtered_groups) # 分组后应用自定义函数 def salary_range(x): return x.max() – x.min() city_salary_range = df.groupby(‘City’)[‘Salary’].apply(salary_range) print(“n各城市薪资范围:”) print(city_salary_range) 输出结果: 各城市平均年龄:CityBerlin    22.0London    30.0New York  26.5Paris     35.0Name: Age, dtype: float64 按城市和年龄分组后的薪资统计:               Salary                   mean   sumCity   Age               Berlin 22.0  4500.0 4500London 30.0  6000.0 6000New York 25.0  5000.0 5000       28.0  5500.0 5500Paris  35.0  7000.0 7000 平均薪资大于5500的城市记录:          Age     City  SalaryName                        Bob        30   London    6000Charlie    35    Paris    7000 各城市薪资范围:CityBerlin      0London      0New York    500Paris       0Name: Salary, dtype: int64
  • Pandas 支持高效的向量化运算,避免显式循环,大幅提高计算效率。 # 单列运算 – 所有年龄加1 df[‘Age’] = df[‘Age’] + 1 print(“年龄加1后的数据集:”) print(df) # 多列运算 – 添加年薪列(假设Salary是月薪) df[‘Annual_Salary’] = df[‘Salary’] * 12 print(“n添加年薪列后的数据集:”) print(df) # 统计函数 print(“n各城市平均年龄:”) print(df.groupby(‘City’)[‘Age’].mean()) print(“n各城市平均年薪:”) print(df.groupby(‘City’)[‘Annual_Salary’].mean()) # 相关系数计算 print(“nAge与Salary的相关系数:”) print(df[‘Age’].corr(df[‘Salary’])) 输出结果: 年龄加1后的数据集:          Age     City  Salary  Annual_SalaryName                                    Alice      26  New York    5000         60000Bob        31   London    6000         72000Charlie    36    Paris    7000         84000David      29  New York    5500         66000Eve        23   Berlin    4500         54000 添加年薪列后的数据集:          Age     City  Salary  Annual_SalaryName                                    Alice      26  New York    5000         60000Bob        31   London    6000         72000Charlie    36    Paris    7000         84000David      29  New York    5500         66000Eve        23   Berlin    4500         54000 各城市平均年龄:CityBerlin    23.0London    31.0New York  27.5Paris     36.0Name: Age, dtype: float64 各城市平均年薪:CityBerlin    54000.0London    72000.0New York  63000.0Paris     84000.0Name: Annual_Salary, dtype: float64 Age与Salary的相关系数:0.9411252628281636
  • Pandas 提供了灵活的接口用于数据框的结构修改,包括列和行的增删改查。 # 添加新列 – 年龄段分类 df[‘Age_Category’] = pd.cut(df[‘Age’], bins=[20, 25, 30, 35, 40], labels=[‘Young’, ‘Early Career’, ‘Mid Career’, ‘Senior’]) print(“添加年龄段分类后的数据集:”) print(df) # 删除列 – 删除Age列 df.drop(‘Age’, axis=1, inplace=True) print(“n删除Age列后的数据集:”) print(df) # 修改数据 – 将New York的薪资提高5% df.loc[df[‘City’] == ‘New York’, ‘Salary’] *= 1.05 print(“n调整New York薪资后的数据集:”) print(df) # 插入行 new_row = pd.DataFrame({ ‘Name’: [‘Frank’], ‘City’: [‘Sydney’], ‘Salary’: [6500], ‘Annual_Salary’: [6500*12], ‘Age_Category’: [‘Mid Career’] }, index=[‘Frank’]) df = pd.concat([df, new_row]) print(“n插入新行后的数据集:”) print(df) 输出结果: 添加年龄段分类后的数据集:          Age     City  Salary  Annual_Salary Age_CategoryName                                                    Alice      26  New York    5000         60000  Early CareerBob        31   London    6000         72000    Mid CareerCharlie    36    Paris    7000         84000     SeniorDavid      29  New York    5500         66000  Early CareerEve        23   Berlin    4500         54000        Young 删除Age列后的数据集:          City  Salary  Annual_Salary Age_CategoryName                                                    Alice  New York    5000         60000  Early CareerBob    London    6000         72000    Mid CareerCharlie   Paris    7000         84000     SeniorDavid  New York    5500         66000  Early CareerEve    Berlin    4500         54000        Young 调整New York薪资后的数据集:          City  Salary  Annual_Salary Age_CategoryName                                                    Alice  New York    5250         63000  Early CareerBob    London    6000         72000    Mid CareerCharlie   Paris    7000         84000     SeniorDavid  New York    5775         69300  Early CareerEve    Berlin    4500         54000        Young 插入新行后的数据集:          City  Salary  Annual_Salary Age_CategoryName                                                    Alice  New York    5250         63000  Early CareerBob    London    6000         72000    Mid CareerCharlie   Paris    7000         84000     SeniorDavid  New York    5775         69300  Early CareerEve    Berlin    4500         54000        YoungFrank  Sydney    6500         78000    Mid Career
  • Pandas 支持多种方式合并不同的数据框,包括内连接、外连接等常见数据库操作。 # 创建第二个数据框 df2 = pd.DataFrame({ ‘Name’: [‘Alice’, ‘Bob’, ‘Charlie’, ‘Frank’], ‘Department’: [‘Engineering’, ‘Marketing’, ‘Engineering’, ‘HR’] }) # 内连接 – 只保留两个数据框都有的Name merged_inner = pd.merge(df, df2, on=’Name’, how=’inner’) print(“内连接结果:”) print(merged_inner) # 左连接 – 保留左数据框的所有记录 merged_left = pd.merge(df, df2, on=’Name’, how=’left’) print(“n左连接结果:”) print(merged_left) # 右连接 – 保留右数据框的所有记录 merged_right = pd.merge(df, df2, on=’Name’, how=’right’) print(“n右连接结果:”) print(merged_right) # 全连接 – 保留两个数据框的所有记录 merged_outer = pd.merge(df, df2, on=’Name’, how=’outer’) print(“n全连接结果:”) print(merged_outer) 输出结果: 内连接结果:          City  Salary  Annual_Salary Age_Category  DepartmentName                                                        Alice  New York    5250         63000  Early Career  EngineeringBob    London    6000         72000    Mid Career   MarketingCharlie   Paris    7000         84000     Senior  EngineeringFrank  Sydney    6500         78000    Mid Career           HR 左连接结果:          City  Salary  Annual_Salary Age_Category DepartmentName                                                        Alice  New York    5250         63000  Early Career  EngineeringBob    London    6000         72000    Mid Career   MarketingCharlie   Paris    7000         84000     Senior  EngineeringDavid  New York    5775         69300  Early Career        NaNEve    Berlin    4500         54000        Young        NaNFrank  Sydney    6500         78000    Mid Career           HR 右连接结果:          City  Salary  Annual_Salary Age_Category  DepartmentName                                                        Alice  New York    5250         63000  Early Career  EngineeringBob    London    6000         72000    Mid Career   MarketingCharlie   Paris    7000         84000     Senior  EngineeringFrank  Sydney    6500         78000    Mid Career           HR 全连接结果:          City  Salary  Annual_Salary Age_Category  DepartmentName                                                        Alice  New York    5250         63000  Early Career  EngineeringBob    London    6000         72000    Mid Career   MarketingCharlie   Paris    7000         84000     Senior  EngineeringDavid  New York    5775         69300  Early Career        NaNEve    Berlin    4500         54000        Young        NaNFrank  Sydney    6500         78000    Mid Career           HR
  • 数据透视表是分析多维数据的强大工具,支持在行、列维度上同时进行分组和聚合。 # 创建示例数据 data = { ‘Year’: [2020, 2020, 2020, 2021, 2021, 2021], ‘Month’: [1, 2, 3, 1, 2, 3], ‘City’: [‘New York’, ‘New York’, ‘London’, ‘New York’, ‘London’, ‘London’], ‘Sales’: [100, 120, 110, 130, 140, 150] } sales_df = pd.DataFrame(data) # 创建基本数据透视表 – 按年和月分组,计算Sales总和 pivot_sales = sales_df.pivot_table( values=’Sales’, index=’Year’, columns=’Month’, aggfunc=’sum’ ) print(“按年和月分组的销售数据透视表:”) print(pivot_sales) # 多层数据透视表 – 同时按年、月和城市分组 multi_pivot = sales_df.pivot_table( values=’Sales’, index=[‘Year’, ‘City’], columns=’Month’, aggfunc=’sum’ ) print(“n按年、城市和月分组的销售数据透视表:”) print(multi_pivot) # 应用多个聚合函数 pivot_agg = sales_df.pivot_table( values=’Sales’, index=’Year’, columns=’City’, aggfunc=[‘sum’, ‘mean’, ‘count’] ) print(“n应用多个聚合函数的数据透视表:”) print(pivot_agg) 输出结果: 按年和月分组的销售数据透视表:Month  1    2    3Year              2020  100  120  1102021  130  140  150 按年、城市和月分组的销售数据透视表:Month           1    2    3Year City                    2020 New York  100  120  NaN     London   NaN  NaN  1102021 New York  130  NaN  NaN     London   NaN  140  150 应用多个聚合函数的数据透视表:           sum       mean  countCity     New York London New York London New York LondonYear                                          2020        220    110     2      1      2      12021        130    290     1      2      1      2
  • Pandas 对时间序列数据提供了强大的支持,包括日期解析、频率转换和时间差计算。 # 创建带时间序列的数据 dates = pd.date_range(start=’2023-01-01′, periods=6, freq=’M’) sales = [100, 120, 110, 130, 140, 150] ts_df = pd.DataFrame({ ‘Date’: dates, ‘Sales’: sales }) # 转换为datetime类型 ts_df[‘Date’] = pd.to_datetime(ts_df[‘Date’]) print(“时间序列数据:”) print(ts_df) # 提取时间特征 ts_df[‘Year’] = ts_df[‘Date’].dt.year ts_df[‘Month’] = ts_df[‘Date’].dt.month ts_df[‘Quarter’] = ts_df[‘Date’].dt.quarter print(“n添加时间特征后:”) print(ts_df) # 时间序列重采样 – 按季度聚合 ts_df.set_index(‘Date’, inplace=True) quarterly_sales = ts_df.resample(‘Q’).sum() print(“n按季度聚合的销售数据:”) print(quarterly_sales) # 计算时间差 ts_df[‘Previous_Sales’] = ts_df[‘Sales’].shift(1) ts_df[‘Sales_Growth’] = ts_df[‘Sales’] – ts_df[‘Previous_Sales’] print(“n添加销售增长数据后:”) print(ts_df) 输出结果: 时间序列数据:        Date  Sales0 2023-01-31    1001 2023-02-28    1202 2023-03-31    1103 2023-04-30    1304 2023-05-31    1405 2023-06-30    150 添加时间特征后:        Date  Sales  Year  Month  Quarter0 2023-01-31    100  2023      1        11 2023-02-28    120  2023      2        12 2023-03-31    110  2023      3        13 2023-04-30    130  2023      4        24 2023-05-31    140  2023      5        25 2023-06-30    150  2023      6        2 按季度聚合的销售数据:            Sales  Year  Month  QuarterDate                                  2023-03-31      330  2023      3        12023-06-30      420  2023      6        2 添加销售增长数据后:            Sales  Year  Month  Quarter  Previous_Sales  Sales_GrowthDate                                                                2023-01-31    100  2023      1        1             NaN          NaN2023-02-28    120  2023      2        1           100.0         20.02023-03-31    110  2023      3        1           120.0        -10.02023-04-30    130  2023      4        2           110.0         20.02023-05-31    140  2023      5        2           130.0         10.02023-06-30    150  2023      6        2           140.0         10.0
  • 处理大规模数据时,Pandas 提供了多种优化方法,包括分块读取、数据类型优化和内存管理。 # 分块读取大文件示例 def process_chunk(chunk): “””处理数据块的示例函数””” return chunk.groupby(‘City’)[‘Salary’].mean() # 模拟大文件分块读取 chunksize = 2 results = [] for chunk in pd.read_csv(‘sample_data.csv’, chunksize=chunksize): results.append(process_chunk(chunk)) # 合并分块处理结果 final_result = pd.concat(results) print(“分块处理结果:”) print(final_result) # 优化数据类型以减少内存占用 df[‘Salary’] = df[‘Salary’].astype(‘int32’) # 从int64转为int32 print(“n优化数据类型后内存使用:”) df.info() # 使用category类型处理分类数据 df[‘City’] = df[‘City’].astype(‘category’) print(“n使用category类型后内存使用:”) df.info() # 稀疏数据处理 sparse_data = pd.Series([0, 0, 0, 5, 0, 0, 10, 0], dtype=’Sparse[int]’) print(“n稀疏数据示例:”) print(sparse_data) 输出结果: 分块处理结果:CityNew York    5000.0London    6000.0New York    5500.0Berlin    4500.0dtype: float64 优化数据类型后内存使用:<class 'pandas.core.frameworks.dataframe.DataFrame'>Index: 5 entries, Alice to FrankData columns (total 4 columns): #   Column        Non-Null Count  Dtype  —  ——        ————–  —–   0   City          5 non-null      object  1   Salary        5 non-null      int32   2   Annual_Salary 5 non-null      int64   3   Age_Category  5 non-null      object dtypes: int32(1), int64(1), object(2)memory usage: 240.0+ bytes 使用category类型后内存使用:<class 'pandas.core.frameworks.dataframe.DataFrame'>Index: 5 entries, Alice to FrankData columns (total 4 columns): #   Column        Non-Null Count  Dtype    —  ——        ————–  —–     0   City          5 non-null      category 1   Salary        5 non-null      int32     2   Annual_Salary 5 non-null      int64     3   Age_Category  5 non-null      object   dtypes: category(1), int32(1), int64(1), object(1)memory usage: 228.0+ bytes 稀疏数据示例:0      01      02      03      54      05      06     107      0dtype: Sparse[int, 0]
  • 目录
    • 1. Pandas 概述
    • 2. 基本操作:数据读取与查看
    • 3. 索引操作:精准定位数据
    • 4. GroupBy 操作:分组聚合分析
    • 5. 数值运算:向量化计算
    • 6. 对象操作:数据增删改查
    • 7. Merge 操作:数据合并
    • 8. 数据透视表:多维数据分析
    • 9. 时间序列处理
    • 10. 大数据处理技巧
    • 学习总结:Pandas 核心函数与方法
      • 1. 数据结构创建
      • 2. 数据查看与信息
      • 3. 索引与筛选
      • 4. 数据操作
      • 5. 分组与聚合
      • 6. 数据合并
      • 7. 时间序列
      • 8. 性能优化

    Pandas 是 Python 数据科学领域的核心库,专为处理结构化数据而设计。它提供了两种核心数据结构:Series(一维数组)和DataFrame(二维表格),支持高效的数据操作、清洗和分析。Pandas 的主要优势包括:

    • 高效处理大型数据集
    • 灵活的数据清洗和转换功能
    • 强大的分组和聚合操作
    • 无缝对接其他科学计算库(如 NumPy、Matplotlib)
    import pandas as pd
    import numpy as np
    # 创建Series(一维数据结构)
    s = pd.Series([1, 3, 5, np.nan, 6, 8])
    print("Series示例:")
    print(s)
    # 创建DataFrame(二维表格)
    df = pd.DataFrame({
        'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'London', 'Paris']
    })
    print("nDataFrame示例:")
    print(df)

    输出结果:

    Series示例:
    0     1.0
    1     3.0
    2     5.0
    3     NaN
    4     6.0
    5     8.0
    dtype: float64

    DataFrame示例:
         Name  Age      City
    0   Alice   25  New York
    1     Bob   30    London
    2  Charlie   35     Paris

    Pandas 提供了丰富的接口用于读取不同格式的数据,并支持便捷的数据探查功能。

    # 构造示例数据
    data = {
        'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'Age': [25, 30, 35, 28, 22],
        'City': ['New York', 'London', 'Paris', 'New York', 'Berlin'],
        'Salary': [5000, 6000, 7000, 5500, 4500]
    }
    df = pd.DataFrame(data)
    # 保存为CSV文件
    df.to_csv('sample_data.csv', index=False)
    # 从CSV读取数据
    df = pd.read_csv('sample_data.csv')
    # 查看数据基本信息
    print("数据基本信息:")
    df.info()
    # 查看数据前几行
    print("n数据前5行:")
    print(df.head())
    # 查看数据统计摘要
    print("n数据统计摘要:")
    print(df.describe())
    # 查看数据形状
    rows, columns = df.shape
    print(f"n数据形状: {rows}行{columns}列")

    输出结果:

    数据基本信息:
    <class 'pandas.core.frameworks.dataframe.DataFrame'>
    RangeIndex: 5 entries, 0 to 4
    Data columns (total 4 columns):
     #   Column  Non-Null Count  Dtype
    —  ——  ————–  —–
     0   Name    5 non-null      object
     1   Age     5 non-null      int64
     2   City    5 non-null      object
     3   Salary  5 non-null      int64
    dtypes: int64(2), object(2)
    memory usage: 240.0+ bytes

    数据前5行:
         Name  Age     City  Salary
    0   Alice   25  New York    5000
    1     Bob   30   London    6000
    2  Charlie   35    Paris    7000
    3   David   28  New York    5500
    4     Eve   22   Berlin    4500

    数据统计摘要:
           Age     Salary
    count  5.0   5.0
    mean   28.0  5600.0
    std     5.0   953.9
    min    22.0  4500.0
    25%    25.0  5000.0
    50%    28.0  5500.0
    75%    30.0  6000.0
    max    35.0  7000.0

    数据形状: 5行4列

    Pandas 支持多种索引方式,包括位置索引、标签索引和布尔索引,满足不同场景的数据访问需求。

    # 位置索引 (iloc)
    print("第一行数据 (iloc[0]):")
    print(df.iloc[0])
    print("n前两行数据 (iloc[:2]):")
    print(df.iloc[:2])
    # 标签索引 (loc)
    df.set_index('Name', inplace=True)
    print("n以Name为索引后,查询Alice的记录 (loc['Alice']):")
    print(df.loc['Alice'])
    # 布尔索引
    print("n年龄大于30的记录:")
    print(df[df['Age'] > 30])
    # 组合索引
    print("n查询New York的高收入人群 (Salary > 5000):")
    print(df[(df['City'] == 'New York') & (df['Salary'] > 5000)])

    输出结果:

    第一行数据 (iloc[0]):
    Name         Alice
    Age            25
    City      New York
    Salary       5000
    Name: 0, dtype: object

    前两行数据 (iloc[:2]):
         Name  Age     City  Salary
    0   Alice   25  New York    5000
    1     Bob   30   London    6000

    以Name为索引后,查询Alice的记录 (loc['Alice']):
    Age            25
    City      New York
    Salary       5000
    Name: Alice, dtype: object

    年龄大于30的记录:
              Age     City  Salary
    Name                        
    Charlie    35    Paris    7000

    查询New York的高收入人群 (Salary > 5000):
              Age     City  Salary
    Name                        
    David      28  New York    5500

    GroupBy 是 Pandas 中最强大的功能之一,支持按指定列分组后进行各种聚合计算。

    # 按City分组,计算平均年龄
    city_age_mean = df.groupby('City')['Age'].mean()
    print("各城市平均年龄:")
    print(city_age_mean)
    # 多列分组并应用多个聚合函数
    grouped = df.groupby(['City', 'Age']).agg({
        'Salary': ['mean', 'sum']
    })
    print("n按城市和年龄分组后的薪资统计:")
    print(grouped)
    # 分组后筛选 - 只保留平均薪资大于5500的城市
    filtered_groups = df.groupby('City').filter(lambda x: x['Salary'].mean() > 5500)
    print("n平均薪资大于5500的城市记录:")
    print(filtered_groups)
    # 分组后应用自定义函数
    def salary_range(x):
        return x.max() - x.min()
    city_salary_range = df.groupby('City')['Salary'].apply(salary_range)
    print("n各城市薪资范围:")
    print(city_salary_range)

    输出结果:

    各城市平均年龄:
    City
    Berlin    22.0
    London    30.0
    New York  26.5
    Paris     35.0
    Name: Age, dtype: float64

    按城市和年龄分组后的薪资统计:
                   Salary      
                 mean   sum
    City   Age               
    Berlin 22.0  4500.0 4500
    London 30.0  6000.0 6000
    New York 25.0  5000.0 5000
           28.0  5500.0 5500
    Paris  35.0  7000.0 7000

    平均薪资大于5500的城市记录:
              Age     City  Salary
    Name                        
    Bob        30   London    6000
    Charlie    35    Paris    7000

    各城市薪资范围:
    City
    Berlin      0
    London      0
    New York    500
    Paris       0
    Name: Salary, dtype: int64

    Pandas 支持高效的向量化运算,避免显式循环,大幅提高计算效率。

    # 单列运算 - 所有年龄加1
    df['Age'] = df['Age'] + 1
    print("年龄加1后的数据集:")
    print(df)
    # 多列运算 - 添加年薪列(假设Salary是月薪)
    df['Annual_Salary'] = df['Salary'] * 12
    print("n添加年薪列后的数据集:")
    print(df)
    # 统计函数
    print("n各城市平均年龄:")
    print(df.groupby('City')['Age'].mean())
    print("n各城市平均年薪:")
    print(df.groupby('City')['Annual_Salary'].mean())
    # 相关系数计算
    print("nAge与Salary的相关系数:")
    print(df['Age'].corr(df['Salary']))

    输出结果:

    年龄加1后的数据集:
              Age     City  Salary  Annual_Salary
    Name                                    
    Alice      26  New York    5000         60000
    Bob        31   London    6000         72000
    Charlie    36    Paris    7000         84000
    David      29  New York    5500         66000
    Eve        23   Berlin    4500         54000

    添加年薪列后的数据集:
              Age     City  Salary  Annual_Salary
    Name                                    
    Alice      26  New York    5000         60000
    Bob        31   London    6000         72000
    Charlie    36    Paris    7000         84000
    David      29  New York    5500         66000
    Eve        23   Berlin    4500         54000

    各城市平均年龄:
    City
    Berlin    23.0
    London    31.0
    New York  27.5
    Paris     36.0
    Name: Age, dtype: float64

    各城市平均年薪:
    City
    Berlin    54000.0
    London    72000.0
    New York  63000.0
    Paris     84000.0
    Name: Annual_Salary, dtype: float64

    Age与Salary的相关系数:
    0.9411252628281636

    Pandas 提供了灵活的接口用于数据框的结构修改,包括列和行的增删改查。

    # 添加新列 - 年龄段分类
    df['Age_Category'] = pd.cut(df['Age'], bins=[20, 25, 30, 35, 40], 
                               labels=['Young', 'Early Career', 'Mid Career', 'Senior'])
    print("添加年龄段分类后的数据集:")
    print(df)
    # 删除列 - 删除Age列
    df.drop('Age', axis=1, inplace=True)
    print("n删除Age列后的数据集:")
    print(df)
    # 修改数据 - 将New York的薪资提高5%
    df.loc[df['City'] == 'New York', 'Salary'] *= 1.05
    print("n调整New York薪资后的数据集:")
    print(df)
    # 插入行
    new_row = pd.DataFrame({
        'Name': ['Frank'],
        'City': ['Sydney'],
        'Salary': [6500],
        'Annual_Salary': [6500*12],
        'Age_Category': ['Mid Career']
    }, index=['Frank'])
    df = pd.concat([df, new_row])
    print("n插入新行后的数据集:")
    print(df)

    输出结果:

    添加年龄段分类后的数据集:
              Age     City  Salary  Annual_Salary Age_Category
    Name                                                    
    Alice      26  New York    5000         60000  Early Career
    Bob        31   London    6000         72000    Mid Career
    Charlie    36    Paris    7000         84000     Senior
    David      29  New York    5500         66000  Early Career
    Eve        23   Berlin    4500         54000        Young

    删除Age列后的数据集:
              City  Salary  Annual_Salary Age_Category
    Name                                                    
    Alice  New York    5000         60000  Early Career
    Bob    London    6000         72000    Mid Career
    Charlie   Paris    7000         84000     Senior
    David  New York    5500         66000  Early Career
    Eve    Berlin    4500         54000        Young

    调整New York薪资后的数据集:
              City  Salary  Annual_Salary Age_Category
    Name                                                    
    Alice  New York    5250         63000  Early Career
    Bob    London    6000         72000    Mid Career
    Charlie   Paris    7000         84000     Senior
    David  New York    5775         69300  Early Career
    Eve    Berlin    4500         54000        Young

    插入新行后的数据集:
              City  Salary  Annual_Salary Age_Category
    Name                                                    
    Alice  New York    5250         63000  Early Career
    Bob    London    6000         72000    Mid Career
    Charlie   Paris    7000         84000     Senior
    David  New York    5775         69300  Early Career
    Eve    Berlin    4500         54000        Young
    Frank  Sydney    6500         78000    Mid Career

    Pandas 支持多种方式合并不同的数据框,包括内连接、外连接等常见数据库操作。

    # 创建第二个数据框
    df2 = pd.DataFrame({
        'Name': ['Alice', 'Bob', 'Charlie', 'Frank'],
        'Department': ['Engineering', 'Marketing', 'Engineering', 'HR']
    })
    # 内连接 - 只保留两个数据框都有的Name
    merged_inner = pd.merge(df, df2, on='Name', how='inner')
    print("内连接结果:")
    print(merged_inner)
    # 左连接 - 保留左数据框的所有记录
    merged_left = pd.merge(df, df2, on='Name', how='left')
    print("n左连接结果:")
    print(merged_left)
    # 右连接 - 保留右数据框的所有记录
    merged_right = pd.merge(df, df2, on='Name', how='right')
    print("n右连接结果:")
    print(merged_right)
    # 全连接 - 保留两个数据框的所有记录
    merged_outer = pd.merge(df, df2, on='Name', how='outer')
    print("n全连接结果:")
    print(merged_outer)

    输出结果:

    内连接结果:
              City  Salary  Annual_Salary Age_Category  Department
    Name                                                        
    Alice  New York    5250         63000  Early Career  Engineering
    Bob    London    6000         72000    Mid Career   Marketing
    Charlie   Paris    7000         84000     Senior  Engineering
    Frank  Sydney    6500         78000    Mid Career           HR

    左连接结果:
              City  Salary  Annual_Salary Age_Category Department
    Name                                                        
    Alice  New York    5250         63000  Early Career  Engineering
    Bob    London    6000         72000    Mid Career   Marketing
    Charlie   Paris    7000         84000     Senior  Engineering
    David  New York    5775         69300  Early Career        NaN
    Eve    Berlin    4500         54000        Young        NaN
    Frank  Sydney    6500         78000    Mid Career           HR

    右连接结果:
              City  Salary  Annual_Salary Age_Category  Department
    Name                                                        
    Alice  New York    5250         63000  Early Career  Engineering
    Bob    London    6000         72000    Mid Career   Marketing
    Charlie   Paris    7000         84000     Senior  Engineering
    Frank  Sydney    6500         78000    Mid Career           HR

    全连接结果:
              City  Salary  Annual_Salary Age_Category  Department
    Name                                                        
    Alice  New York    5250         63000  Early Career  Engineering
    Bob    London    6000         72000    Mid Career   Marketing
    Charlie   Paris    7000         84000     Senior  Engineering
    David  New York    5775         69300  Early Career        NaN
    Eve    Berlin    4500         54000        Young        NaN
    Frank  Sydney    6500         78000    Mid Career           HR

    数据透视表是分析多维数据的强大工具,支持在行、列维度上同时进行分组和聚合。

    # 创建示例数据
    data = {
        'Year': [2020, 2020, 2020, 2021, 2021, 2021],
        'Month': [1, 2, 3, 1, 2, 3],
        'City': ['New York', 'New York', 'London', 'New York', 'London', 'London'],
        'Sales': [100, 120, 110, 130, 140, 150]
    }
    sales_df = pd.DataFrame(data)
    # 创建基本数据透视表 - 按年和月分组,计算Sales总和
    pivot_sales = sales_df.pivot_table(
        values='Sales', 
        index='Year', 
        columns='Month', 
        aggfunc='sum'
    )
    print("按年和月分组的销售数据透视表:")
    print(pivot_sales)
    # 多层数据透视表 - 同时按年、月和城市分组
    multi_pivot = sales_df.pivot_table(
        values='Sales', 
        index=['Year', 'City'], 
        columns='Month', 
        aggfunc='sum'
    )
    print("n按年、城市和月分组的销售数据透视表:")
    print(multi_pivot)
    # 应用多个聚合函数
    pivot_agg = sales_df.pivot_table(
        values='Sales', 
        index='Year', 
        columns='City', 
        aggfunc=['sum', 'mean', 'count']
    )
    print("n应用多个聚合函数的数据透视表:")
    print(pivot_agg)

    输出结果:

    按年和月分组的销售数据透视表:
    Month  1    2    3
    Year              
    2020  100  120  110
    2021  130  140  150

    按年、城市和月分组的销售数据透视表:
    Month           1    2    3
    Year City                    
    2020 New York  100  120  NaN
         London   NaN  NaN  110
    2021 New York  130  NaN  NaN
         London   NaN  140  150

    应用多个聚合函数的数据透视表:
               sum       mean  count
    City     New York London New York London New York London
    Year                                          
    2020        220    110     2      1      2      1
    2021        130    290     1      2      1      2

    Pandas 对时间序列数据提供了强大的支持,包括日期解析、频率转换和时间差计算。

    # 创建带时间序列的数据
    dates = pd.date_range(start='2023-01-01', periods=6, freq='M')
    sales = [100, 120, 110, 130, 140, 150]
    ts_df = pd.DataFrame({
        'Date': dates,
        'Sales': sales
    })
    # 转换为datetime类型
    ts_df['Date'] = pd.to_datetime(ts_df['Date'])
    print("时间序列数据:")
    print(ts_df)
    # 提取时间特征
    ts_df['Year'] = ts_df['Date'].dt.year
    ts_df['Month'] = ts_df['Date'].dt.month
    ts_df['Quarter'] = ts_df['Date'].dt.quarter
    print("n添加时间特征后:")
    print(ts_df)
    # 时间序列重采样 - 按季度聚合
    ts_df.set_index('Date', inplace=True)
    quarterly_sales = ts_df.resample('Q').sum()
    print("n按季度聚合的销售数据:")
    print(quarterly_sales)
    # 计算时间差
    ts_df['Previous_Sales'] = ts_df['Sales'].shift(1)
    ts_df['Sales_Growth'] = ts_df['Sales'] - ts_df['Previous_Sales']
    print("n添加销售增长数据后:")
    print(ts_df)

    输出结果:

    时间序列数据:
            Date  Sales
    0 2023-01-31    100
    1 2023-02-28    120
    2 2023-03-31    110
    3 2023-04-30    130
    4 2023-05-31    140
    5 2023-06-30    150

    添加时间特征后:
            Date  Sales  Year  Month  Quarter
    0 2023-01-31    100  2023      1        1
    1 2023-02-28    120  2023      2        1
    2 2023-03-31    110  2023      3        1
    3 2023-04-30    130  2023      4        2
    4 2023-05-31    140  2023      5        2
    5 2023-06-30    150  2023      6        2

    按季度聚合的销售数据:
                Sales  Year  Month  Quarter
    Date                                  
    2023-03-31      330  2023      3        1
    2023-06-30      420  2023      6        2

    添加销售增长数据后:
                Sales  Year  Month  Quarter  Previous_Sales  Sales_Growth
    Date                                                                
    2023-01-31    100  2023      1        1             NaN          NaN
    2023-02-28    120  2023      2        1           100.0         20.0
    2023-03-31    110  2023      3        1           120.0        -10.0
    2023-04-30    130  2023      4        2           110.0         20.0
    2023-05-31    140  2023      5        2           130.0         10.0
    2023-06-30    150  2023      6        2           140.0         10.0

    处理大规模数据时,Pandas 提供了多种优化方法,包括分块读取、数据类型优化和内存管理。

    # 分块读取大文件示例
    def process_chunk(chunk):
        """处理数据块的示例函数"""
        return chunk.groupby('City')['Salary'].mean()
    # 模拟大文件分块读取
    chunksize = 2
    results = []
    for chunk in pd.read_csv('sample_data.csv', chunksize=chunksize):
        results.append(process_chunk(chunk))
    # 合并分块处理结果
    final_result = pd.concat(results)
    print("分块处理结果:")
    print(final_result)
    # 优化数据类型以减少内存占用
    df['Salary'] = df['Salary'].astype('int32')  # 从int64转为int32
    print("n优化数据类型后内存使用:")
    df.info()
    # 使用category类型处理分类数据
    df['City'] = df['City'].astype('category')
    print("n使用category类型后内存使用:")
    df.info()
    # 稀疏数据处理
    sparse_data = pd.Series([0, 0, 0, 5, 0, 0, 10, 0], dtype='Sparse[int]')
    print("n稀疏数据示例:")
    print(sparse_data)

    输出结果:

    分块处理结果:
    City
    New York    5000.0
    London    6000.0
    New York    5500.0
    Berlin    4500.0
    dtype: float64

    优化数据类型后内存使用:
    <class 'pandas.core.frameworks.dataframe.DataFrame'>
    Index: 5 entries, Alice to Frank
    Data columns (total 4 columns):
     #   Column        Non-Null Count  Dtype  
    —  ——        ————–  —–  
     0   City          5 non-null      object 
     1   Salary        5 non-null      int32  
     2   Annual_Salary 5 non-null      int64  
     3   Age_Category  5 non-null      object 
    dtypes: int32(1), int64(1), object(2)
    memory usage: 240.0+ bytes

    使用category类型后内存使用:
    <class 'pandas.core.frameworks.dataframe.DataFrame'>
    Index: 5 entries, Alice to Frank
    Data columns (total 4 columns):
     #   Column        Non-Null Count  Dtype    
    —  ——        ————–  —–    
     0   City          5 non-null      category
     1   Salary        5 non-null      int32    
     2   Annual_Salary 5 non-null      int64    
     3   Age_Category  5 non-null      object   
    dtypes: category(1), int32(1), int64(1), object(1)
    memory usage: 228.0+ bytes

    稀疏数据示例:
    0      0
    1      0
    2      0
    3      5
    4      0
    5      0
    6     10
    7      0
    dtype: Sparse[int, 0]

    • pd.Series(data):创建一维 Series 对象
    • pd.DataFrame(data):创建二维 DataFrame 对象
    • pd.read_csv(filepath):从 CSV 文件读取数据
    • pd.read_excel(filepath):从 Excel 文件读取数据
    • pd.date_range(start, periods, freq):创建日期范围

    • df.info():查看数据基本信息
    • df.head(n):查看前 n 行数据
    • df.tail(n):查看后 n 行数据
    • df.describe():生成描述性统计
    • df.shape:获取数据行列数

    • df.iloc[]:基于位置的索引
    • df.loc[]:基于标签的索引
    • df[condition]:布尔索引
    • df.set_index(col):设置指定列为索引
    • df.reset_index():重置索引

    • df.drop(col, axis=1):删除列
    • df.assign(new_col=value):添加新列
    • df.rename(columns={}):重命名列
    • df.append(row):添加行
    • df.concat([df1, df2]):拼接数据框

    • df.groupby(col):按列分组
    • grouped.agg(func):应用聚合函数
    • grouped.apply(func):应用自定义函数
    • df.pivot_table():创建数据透视表
    • grouped.filter(func):分组后筛选

    • pd.merge(df1, df2, on=col):合并数据框
    • df.join(df2):按索引合并
    • pd.concat([df1, df2]):拼接数据框
    • df.append(row):添加行数据

    • pd.to_datetime(col):转换为日期时间
    • df.resample(freq):时间序列重采样
    • df.shift(n):数据位移
    • df.diff():计算差分
    • pd.date_range():生成日期范围

    • df.chunked = pd.read_csv(..., chunksize=):分块读取
    • df.astype(dtype):优化数据类型
    • df[col] = df[col].astype('category'):使用分类类型
    • pd.SparseSeries():处理稀疏数据

    到此这篇关于python panda库从基础到高级操作的文章就介绍到这了,更多相关python panda库内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • Python pandas库自学超详细教程
    • Python安装Pandas库的两种方法
    • Python进阶学习之pandas中read_csv()用法详解
    • Python Pandas学习之series的二元运算详解
    • Python Pandas学习之Pandas数据结构详解
    • python机器学习使数据更鲜活的可视化工具Pandas_Alive
    • python pandas模块基础学习详解
    • Python学习笔记之pandas索引列、过滤、分组、求和功能示例
    • 详解Python学习之安装pandas

    站内搜索