import pandas as pd
import numpy as np
import matplotlib

matplotlib.use('Agg')  # 使用非交互式后端
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import os

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


class PandasExamples:
    """Pandas数据处理示例类"""

    def __init__(self):
        self.output_dir = 'output'
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

    def create_sample_data(self):
        """创建示例数据文件"""
        print("正在创建示例数据文件...")

        # 创建包含缺失值和重复值的CSV文件
        data_with_issues = pd.DataFrame({
            '姓名': ['张三', '李四', '王五', '张三', '赵六', None, '钱七'],
            '年龄': [23, 45, 12, 23, 35, 28, None],
            '城市': ['北京', '上海', '广州', '北京', '深圳', '杭州', '成都'],
            '销售额': [1000, 2000, 1500, 1000, 3000, 2500, 1800]
        })
        data_with_issues.to_csv(f'data/data.csv', index=False, encoding='utf-8')

        # 创建销售数据
        sales_data = pd.DataFrame({
            '地区': ['东区', '西区', '南区', '北区', '东区', '西区', '南区', '北区'],
            '月份': ['2023-01', '2023-01', '2023-01', '2023-01',
                   '2023-02', '2023-02', '2023-02', '2023-02'],
            '销售额': [100, 200, 150, 300, 400, 250, 180, 320],
            '产品': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B']
        })
        sales_data.to_csv(f'data/sales_data.csv', index=False, encoding='utf-8')

        print("示例数据文件创建完成!")

    def scenario_1_data_cleaning(self):
        """场景一:数据清洗"""
        print("\n=== 场景一:数据清洗 ===")

        # 读取数据
        data = pd.read_csv(f'data/data.csv')
        print("原始数据:")
        print(data)
        print(f"原始数据形状: {data.shape}")

        # 处理缺失值
        data_cleaned = data.dropna()
        print("\n删除缺失值后:")
        print(data_cleaned)

        # 去除重复值
        data_cleaned = data_cleaned.drop_duplicates()
        print("\n去除重复值后:")
        print(data_cleaned)
        print(f"清洗后数据形状: {data_cleaned.shape}")

        return data_cleaned

    def scenario_2_data_type_conversion(self):
        """场景二:数据类型转换"""
        print("\n=== 场景二:数据类型转换 ===")

        # 示例数据
        data = {
            'A': ['1', '2', '3'],
            'B': ['4.1', '5.2', '6.3'],
            'C': ['2023-01-01', '2023-02-01', '2023-03-01']
        }
        df = pd.DataFrame(data)
        print("转换前数据类型:")
        print(df.dtypes)

        # 数据类型转换
        df['A'] = df['A'].astype(int)
        df['B'] = df['B'].astype(float)
        df['C'] = pd.to_datetime(df['C'])

        print("\n转换后数据类型:")
        print(df.dtypes)
        print("\n转换后的数据:")
        print(df)

        return df

    def scenario_3_data_merging(self):
        """场景三:数据合并"""
        print("\n=== 场景三:数据合并 ===")

        # 示例数据
        data1 = {'key': ['A', 'B', 'C'], 'value1': [1, 2, 3]}
        data2 = {'key': ['A', 'B', 'D'], 'value2': [4, 5, 6]}
        df1 = pd.DataFrame(data1)
        df2 = pd.DataFrame(data2)

        print("数据集1:")
        print(df1)
        print("\n数据集2:")
        print(df2)

        # 数据合并
        merged_data = pd.merge(df1, df2, on='key', how='inner')
        print("\n合并后的数据:")
        print(merged_data)

        return merged_data

    def scenario_4_grouping_aggregation(self):
        """场景四:数据分组与聚合"""
        print("\n=== 场景四:数据分组与聚合 ===")

        # 读取销售数据
        df = pd.read_csv(f'data/sales_data.csv')
        print("原始销售数据:")
        print(df)

        # 数据分组与聚合
        grouped_data = df.groupby(['地区', '月份']).sum().reset_index()
        print("\n按地区和月份分组聚合后的数据:")
        print(grouped_data)

        # 可视化
        plt.figure(figsize=(10, 6))
        sns.barplot(data=grouped_data, x='地区', y='销售额', hue='月份')
        plt.title('各地区月度销售额对比')
        plt.savefig(f'data/grouping_aggregation.png')
        plt.close()

        return grouped_data

    def scenario_5_data_filtering(self):
        """场景五:数据筛选"""
        print("\n=== 场景五:数据筛选 ===")

        # 示例数据
        data = {
            '姓名': ['张三', '李四', '王五', '赵六'],
            '年龄': [23, 45, 12, 35],
            '城市': ['北京', '上海', '广州', '深圳']
        }
        df = pd.DataFrame(data)
        print("原始数据:")
        print(df)

        # 筛选年龄大于30岁的行
        filtered_data = df[df['年龄'] > 30]
        print("\n筛选后数据 (年龄>30):")
        print(filtered_data)

        return filtered_data

    def scenario_6_pivot_table(self):
        """场景六:数据透视表"""
        print("\n=== 场景六:数据透视表 ===")

        # 示例数据
        data = {
            '产品': ['A', 'B', 'A', 'B', 'A', 'B'],
            '销售员': ['张三', '李四', '王五', '赵六', '张三', '李四'],
            '销售额': [100, 200, 150, 300, 400, 250]
        }
        df = pd.DataFrame(data)
        print("原始数据:")
        print(df)

        # 生成透视表
        pivot_table = pd.pivot_table(df, values='销售额', index=['产品'],
                                     columns=['销售员'], aggfunc='sum', fill_value=0)
        print("\n数据透视表:")
        print(pivot_table)

        # 可视化透视表
        plt.figure(figsize=(8, 6))
        sns.heatmap(pivot_table, annot=True, fmt='d', cmap='YlOrRd')
        plt.title('产品销售透视表')
        plt.savefig(f'data/pivot_table_heatmap.png')
        plt.close()

        return pivot_table

    def scenario_7_time_series_analysis(self):
        """场景七:时间序列分析"""
        print("\n=== 场景七:时间序列分析 ===")

        # 示例数据
        data = {
            '日期': pd.date_range(start='2023-01-01', periods=10, freq='D'),
            '销售额': [100, 200, 150, 300, 400, 250, 300, 350, 200, 150]
        }
        df = pd.DataFrame(data)
        print("原始时间序列数据:")
        print(df)

        # 设置日期为索引
        df.set_index('日期', inplace=True)

        # 计算7天移动平均值
        df['移动平均'] = df['销售额'].rolling(window=7).mean()
        print("\n添加移动平均后的数据:")
        print(df)

        # 可视化时间序列
        plt.figure(figsize=(12, 6))
        plt.plot(df.index, df['销售额'], marker='o', label='原始销售额')
        plt.plot(df.index, df['移动平均'], marker='s', label='7天移动平均')
        plt.title('销售额时间序列分析')
        plt.xlabel('日期')
        plt.ylabel('销售额')
        plt.legend()
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig(f'data/time_series_analysis.png')
        plt.close()

        return df

    def scenario_8_data_reshaping(self):
        """场景八:数据重塑"""
        print("\n=== 场景八:数据重塑 ===")

        # 示例数据
        data = {
            '日期': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'],
            '变量': ['A', 'B', 'A', 'B'],
            '值': [10, 20, 30, 40]
        }
        df = pd.DataFrame(data)
        print("原始长格式数据:")
        print(df)

        # 重塑数据
        reshaped_data = df.pivot(index='日期', columns='变量', values='值')
        print("\n重塑为宽格式后的数据:")
        print(reshaped_data)

        return reshaped_data

    def scenario_9_missing_value_handling(self):
        """场景九:缺失值处理"""
        print("\n=== 场景九:缺失值处理 ===")

        # 示例数据
        data = {
            'A': [1, 2, None, 4],
            'B': [None, 2, 3, 4],
            'C': [1, None, None, 4]
        }
        df = pd.DataFrame(data)
        print("原始数据 (包含缺失值):")
        print(df)

        # 填充缺失值
        df_filled = df.ffill()
        print("\n向前填充缺失值后的数据:")
        print(df_filled)

        # 其他填充方法示例
        df_mean = df.fillna(df.mean())
        print("\n使用均值填充缺失值后的数据:")
        print(df_mean)

        return df_filled

    def scenario_10_data_joining(self):
        """场景十:数据合并与连接"""
        print("\n=== 场景十:数据合并与连接 ===")

        # 示例数据
        left_data = {
            'key': ['K0', 'K1', 'K2', 'K3'],
            'A': ['A0', 'A1', 'A2', 'A3'],
            'B': ['B0', 'B1', 'B2', 'B3']
        }
        right_data = {
            'key': ['K0', 'K1', 'K2', 'K4'],
            'C': ['C0', 'C1', 'C2', 'C4'],
            'D': ['D0', 'D1', 'D2', 'D4']
        }
        left = pd.DataFrame(left_data)
        right = pd.DataFrame(right_data)

        print("左表数据:")
        print(left)
        print("\n右表数据:")
        print(right)

        # 左连接
        result_left = pd.merge(left, right, how='left', on='key')
        print("\n左连接结果:")
        print(result_left)

        # 内连接
        result_inner = pd.merge(left, right, how='inner', on='key')
        print("\n内连接结果:")
        print(result_inner)

        # 外连接
        result_outer = pd.merge(left, right, how='outer', on='key')
        print("\n外连接结果:")
        print(result_outer)

        return result_left

    def run_all_scenarios(self):
        """运行所有场景"""
        print("🚀 开始运行Pandas高效数据处理与分析应用实例")
        print("=" * 60)

        # 创建示例数据
        self.create_sample_data()

        # 运行所有场景
        results = {}
        results['cleaning'] = self.scenario_1_data_cleaning()
        results['conversion'] = self.scenario_2_data_type_conversion()
        results['merging'] = self.scenario_3_data_merging()
        results['grouping'] = self.scenario_4_grouping_aggregation()
        results['filtering'] = self.scenario_5_data_filtering()
        results['pivot'] = self.scenario_6_pivot_table()
        results['time_series'] = self.scenario_7_time_series_analysis()
        results['reshaping'] = self.scenario_8_data_reshaping()
        results['missing'] = self.scenario_9_missing_value_handling()
        results['joining'] = self.scenario_10_data_joining()

        print("\n" + "=" * 60)
        print("✅ 所有场景运行完成!")
        print(f"📊 结果已保存到 {self.output_dir}/ 目录")
        print("📈 图表文件已生成")

        return results


if __name__ == "__main__":
    examples = PandasExamples()
    results = examples.run_all_scenarios()
C:\Users\zyk\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/zyk/PycharmProjects/pythonProject/test2.py
🚀 开始运行Pandas高效数据处理与分析应用实例
============================================================
正在创建示例数据文件...
示例数据文件创建完成!

=== 场景一:数据清洗 ===
原始数据:
    姓名    年龄  城市   销售额
0   张三  23.0  北京  1000
1   李四  45.0  上海  2000
2   王五  12.0  广州  1500
3   张三  23.0  北京  1000
4   赵六  35.0  深圳  3000
5  NaN  28.0  杭州  2500
6   钱七   NaN  成都  1800
原始数据形状: (7, 4)

删除缺失值后:
   姓名    年龄  城市   销售额
0  张三  23.0  北京  1000
1  李四  45.0  上海  2000
2  王五  12.0  广州  1500
3  张三  23.0  北京  1000
4  赵六  35.0  深圳  3000

去除重复值后:
   姓名    年龄  城市   销售额
0  张三  23.0  北京  1000
1  李四  45.0  上海  2000
2  王五  12.0  广州  1500
4  赵六  35.0  深圳  3000
清洗后数据形状: (4, 4)

=== 场景二:数据类型转换 ===
转换前数据类型:
A    object
B    object
C    object
dtype: object

转换后数据类型:
A             int64
B           float64
C    datetime64[ns]
dtype: object

转换后的数据:
   A    B          C
0  1  4.1 2023-01-01
1  2  5.2 2023-02-01
2  3  6.3 2023-03-01

=== 场景三:数据合并 ===
数据集1:
  key  value1
0   A       1
1   B       2
2   C       3

数据集2:
  key  value2
0   A       4
1   B       5
2   D       6

合并后的数据:
  key  value1  value2
0   A       1       4
1   B       2       5

=== 场景四:数据分组与聚合 ===
原始销售数据:
   地区       月份  销售额 产品
0  东区  2023-01  100  A
1  西区  2023-01  200  B
2  南区  2023-01  150  A
3  北区  2023-01  300  B
4  东区  2023-02  400  A
5  西区  2023-02  250  B
6  南区  2023-02  180  A
7  北区  2023-02  320  B

按地区和月份分组聚合后的数据:
   地区       月份  销售额 产品
0  东区  2023-01  100  A
1  东区  2023-02  400  A
2  北区  2023-01  300  B
3  北区  2023-02  320  B
4  南区  2023-01  150  A
5  南区  2023-02  180  A
6  西区  2023-01  200  B
7  西区  2023-02  250  B

=== 场景五:数据筛选 ===
原始数据:
   姓名  年龄  城市
0  张三  23  北京
1  李四  45  上海
2  王五  12  广州
3  赵六  35  深圳

筛选后数据 (年龄>30):
   姓名  年龄  城市
1  李四  45  上海
3  赵六  35  深圳

=== 场景六:数据透视表 ===
原始数据:
  产品 销售员  销售额
0  A  张三  100
1  B  李四  200
2  A  王五  150
3  B  赵六  300
4  A  张三  400
5  B  李四  250

数据透视表:
销售员   张三   李四   王五   赵六
产品                     
A    500    0  150    0
B      0  450    0  300

=== 场景七:时间序列分析 ===
原始时间序列数据:
          日期  销售额
0 2023-01-01  100
1 2023-01-02  200
2 2023-01-03  150
3 2023-01-04  300
4 2023-01-05  400
5 2023-01-06  250
6 2023-01-07  300
7 2023-01-08  350
8 2023-01-09  200
9 2023-01-10  150

添加移动平均后的数据:
            销售额        移动平均
日期                         
2023-01-01  100         NaN
2023-01-02  200         NaN
2023-01-03  150         NaN
2023-01-04  300         NaN
2023-01-05  400         NaN
2023-01-06  250         NaN
2023-01-07  300  242.857143
2023-01-08  350  278.571429
2023-01-09  200  278.571429
2023-01-10  150  278.571429

=== 场景八:数据重塑 ===
原始长格式数据:
           日期 变量   值
0  2023-01-01  A  10
1  2023-01-01  B  20
2  2023-01-02  A  30
3  2023-01-02  B  40

重塑为宽格式后的数据:
变量           A   B
日期                
2023-01-01  10  20
2023-01-02  30  40

=== 场景九:缺失值处理 ===
原始数据 (包含缺失值):
     A    B    C
0  1.0  NaN  1.0
1  2.0  2.0  NaN
2  NaN  3.0  NaN
3  4.0  4.0  4.0

向前填充缺失值后的数据:
     A    B    C
0  1.0  NaN  1.0
1  2.0  2.0  1.0
2  2.0  3.0  1.0
3  4.0  4.0  4.0

使用均值填充缺失值后的数据:
          A    B    C
0  1.000000  3.0  1.0
1  2.000000  2.0  2.5
2  2.333333  3.0  2.5
3  4.000000  4.0  4.0

=== 场景十:数据合并与连接 ===
左表数据:
  key   A   B
0  K0  A0  B0
1  K1  A1  B1
2  K2  A2  B2
3  K3  A3  B3

右表数据:
  key   C   D
0  K0  C0  D0
1  K1  C1  D1
2  K2  C2  D2
3  K4  C4  D4

左连接结果:
  key   A   B    C    D
0  K0  A0  B0   C0   D0
1  K1  A1  B1   C1   D1
2  K2  A2  B2   C2   D2
3  K3  A3  B3  NaN  NaN

内连接结果:
  key   A   B   C   D
0  K0  A0  B0  C0  D0
1  K1  A1  B1  C1  D1
2  K2  A2  B2  C2  D2

外连接结果:
  key    A    B    C    D
0  K0   A0   B0   C0   D0
1  K1   A1   B1   C1   D1
2  K2   A2   B2   C2   D2
3  K3   A3   B3  NaN  NaN
4  K4  NaN  NaN   C4   D4

============================================================
✅ 所有场景运行完成!
📊 结果已保存到 output/ 目录
📈 图表文件已生成

进程已结束,退出代码0

更多推荐