Python语言数据分析入门-10天学会Python
Python语言广泛用于数据分析领域,有丰富的软件库和强大的社区支持。
数据分析核心库
库名 | 用途 |
NumPy | 数值计算 (数组操作、矩阵运算) |
Pandas | 数据处理 (数据清洗、分析、操作) |
Matplotlib | 数据可视化(绘制图表) |
Seaborn | 高级数据可视化 (基于Matplotlib) |
Scikit-learn | 机器学习( 分类、回归、聚类等) |
安装库
pip install numpy pandas matplotlib seaborn scikit-learn
数据分析基本操作
NumPy
- 用途: 提供支持大型多维数组和矩阵运算的函数库,核心是ndarray(多维数组)。
- 特点: 高效的数值计算能力,支持大量的数学函数。
import numpy as np
# 创建数组
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# 数组运算
arr2 = arr + 2
print(arr2) # 输出:[3 4 5 6 7]
# 矩阵运算
matrix = np.array([[1, 2], [3, 4]])
print(matrix * 2) # 输出:[[2 4], [6 8]]
Pandas
- 用途: 提供数据结构和数据分析工具,特别是数据框(DataFrame)。
- 特点: 易于处理和分析结构化数据,支持数据清洗、转换和聚合。
import pandas as pd
# 创建DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
# 读取CSV文件
df = pd.read_csv('data.csv')
# 数据筛选
print(df[df['Age'] > 30]) # 筛选年龄大于30的行
# 数据统计
print(df.describe()) # 输出统计信息(均值、标准差等)
Matplotlib
- 用途: 用于绘制各种静态、动态和交互式图表。
- 特点: 灵活且功能强大,支持多种图表类型。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sample Plot')
plt.show()
Seaborn
- 用途: 基于 Matplotlib 的高级可视化库,提供更美观的图表。
- 特点: 简化了复杂图表的创建,支持统计图表。
import seaborn as sns
# 加载示例数据集
tips = sns.load_dataset('tips')
# 绘制散点图
sns.scatterplot(x='total_bill', y='tip', data=tips)
plt.show()