python数据分析

以下是针对阶段1:基础工具速成的详细知识点讲解,涵盖Python基础、NumPy、Pandas和Matplotlib的核心内容,配合代码示例帮助你快速理解。


1. Python基础

(1)列表/字典/切片

  • 列表(List):有序可变集合,用方括号 [] 定义。
    my_list = [1, 2, 'a', True]
    print(my_list[1:3])  # 切片输出: [2, 'a']
    
  • 字典(Dict):键值对集合,用花括号 {} 定义。
    my_dict = {'name': 'Alice', 'age': 25}
    print(my_dict['name'])  # 输出: Alice
    
  • 切片(Slicing):适用于列表、字符串等,语法 [start:end:step]
    s = "hello"
    print(s[1:4])  # 输出: 'ell'
    

(2)循环和条件语句

  • for 循环
    for i in range(3):  # 输出 0, 1, 2
        print(i)
    
  • if 条件
    x = 10
    if x > 5:
        print("x大于5")
    

(3)函数和lambda表达式

  • 函数
    def add(a, b):
        return a + b
    print(add(2, 3))  # 输出: 5
    
  • Lambda:匿名函数,简化代码。
    square = lambda x: x ** 2
    print(square(4))  # 输出: 16
    

2. NumPy核心操作

(1)数组创建

  • np.array():从列表创建数组。
    import numpy as np
    arr = np.array([1, 2, 3])  # 一维数组
    
  • np.arange():生成等差序列。
    arr = np.arange(0, 10, 2)  # 输出: [0, 2, 4, 6, 8]
    

(2)索引和切片

  • 基本索引:
    arr = np.array([[1, 2], [3, 4]])
    print(arr[0, 1])  # 输出: 2(第0行第1列)
    
  • 切片:
    arr = np.arange(10)
    print(arr[2:5])  # 输出: [2, 3, 4]
    

(3)形状操作

  • reshape:改变数组形状。
    arr = np.arange(6).reshape(2, 3)  # 2行3列
    
  • flatten:展开为一维数组。
    print(arr.flatten())  # 输出: [0, 1, 2, 3, 4, 5]
    

(4)常用函数

  • 统计函数
    arr = np.array([1, 2, 3])
    print(arr.mean())  # 均值: 2.0
    print(arr.sum())   # 求和: 6
    

3. Pandas数据处理

(1)DataFrame操作

  • 创建DataFrame
    import pandas as pd
    df = pd.DataFrame({'A': [1, 2], 'B': ['x', 'y']})
    
  • 查看数据
    print(df.head())  # 查看前5行
    print(df.shape)   # 输出行列数 (2, 2)
    

(2)数据筛选

  • lociloc
    print(df.loc[0, 'A'])  # 输出: 1(按标签)
    print(df.iloc[0, 0])   # 输出: 1(按位置)
    

(3)合并数据

  • merge:类似SQL的JOIN。
    df1 = pd.DataFrame({'key': ['A', 'B'], 'value': [1, 2]})
    df2 = pd.DataFrame({'key': ['A', 'C'], 'value': [3, 4]})
    print(pd.merge(df1, df2, on='key', how='left'))
    

(4)分组聚合

  • groupby
    df = pd.DataFrame({'group': ['A', 'A', 'B'], 'value': [1, 2, 3]})
    print(df.groupby('group').mean())  # 按组求均值
    

4. Matplotlib绘图

(1)折线图

import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [2, 5, 3]
plt.plot(x, y, label='line')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.legend()
plt.show()

(2)散点图

plt.scatter(x, y, color='red', marker='o')
plt.show()

(3)图表定制

  • 标题和标签
    plt.title("示例标题")
    plt.xlabel("X轴标签")
    

重点总结表

工具 核心知识点 关键函数/方法示例
Python 列表切片、循环、lambda list[1:3], lambda x: x+1
NumPy 数组创建、索引、统计 np.arange(), arr.mean()
Pandas DataFrame、合并、分组 df.merge(), groupby()
**Matplotlib 折线图、散点图、标签 plt.plot(), plt.xlabel()

下一步建议

  1. 立即实践:在Jupyter Notebook中逐行运行上述代码,观察输出。
  2. 调试修改:尝试修改代码(如调整切片范围、改变图表颜色),理解每个参数的作用。
  3. 结合项目:用Kaggle数据集实战练习(如分析电影评分数据)。

如果有具体问题(如“如何用Pandas处理缺失值”),可以随时提问!

posted @ 2025-05-23 16:01  flysusdjd  阅读(14)  评论(0)    收藏  举报