Python数据分析:NumPy、Pandas与Matplotlib库
Python 是一种强大的编程语言,特别适合数据分析,主要得益于其丰富的库生态系统。NumPy、Pandas 和 Matplotlib 是 Python 中最常用的数据分析库。以下是对这三个库的简要介绍以及相应的代码示例。
·
Python 是一种强大的编程语言,特别适合数据分析,主要得益于其丰富的库生态系统。NumPy、Pandas 和 Matplotlib 是 Python 中最常用的数据分析库。以下是对这三个库的简要介绍以及相应的代码示例。
1. NumPy
NumPy 是 Python 的一个基本库,用于处理大型多维数组和矩阵,支持大量的高级数学函数。
python复制代码
import numpy as np |
|
# 创建一个 NumPy 数组 |
|
arr = np.array([1, 2, 3, 4, 5]) |
|
print(arr) |
|
# 执行数学运算 |
|
arr_squared = arr ** 2 |
|
print(arr_squared) |
|
# 创建二维数组(矩阵) |
|
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
|
print(matrix) |
|
# 执行矩阵运算 |
|
matrix_transposed = matrix.T |
|
print(matrix_transposed) |
2. Pandas
Pandas 是一个提供数据结构和数据分析工具的 Python 库。它使得数据处理变得简单、直观。
python复制代码
import pandas as pd |
|
# 创建一个 Pandas DataFrame |
|
data = { |
|
'Name': ['Alice', 'Bob', 'Charlie', 'David'], |
|
'Age': [25, 30, 35, 40], |
|
'City': ['New York', 'Paris', 'London', 'Berlin'] |
|
} |
|
df = pd.DataFrame(data) |
|
print(df) |
|
# 数据筛选 |
|
df_over_30 = df[df['Age'] > 30] |
|
print(df_over_30) |
|
# 数据分组和聚合 |
|
grouped = df.groupby('City') |
|
city_counts = grouped['Name'].count() |
|
print(city_counts) |
3. Matplotlib
Matplotlib 是一个用于创建静态、动画和交互式可视化的 Python 库。
python复制代码
import matplotlib.pyplot as plt |
|
# 简单的线图 |
|
x = np.linspace(0, 10, 100) |
|
y = np.sin(x) |
|
plt.plot(x, y) |
|
plt.title("Simple Line Plot") |
|
plt.xlabel("X-axis") |
|
plt.ylabel("Y-axis") |
|
plt.show() |
|
# 柱状图 |
|
categories = ['Category1', 'Category2', 'Category3', 'Category4'] |
|
values = [23, 45, 56, 12] |
|
plt.bar(categories, values) |
|
plt.title("Bar Chart") |
|
plt.xlabel("Categories") |
|
plt.ylabel("Values") |
|
plt.show() |
这些库通常一起使用,以执行复杂的数据分析和可视化任务。例如,你可能首先使用 Pandas 来清洗和整理数据,然后使用 NumPy 进行数值计算,最后使用 Matplotlib 来可视化结果。

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)