首页
/ 使用Pandas探索NBA数据集:从入门到实践

使用Pandas探索NBA数据集:从入门到实践

2026-02-04 04:40:35作者:管翌锬

环境准备

在开始之前,我们需要确保环境已经正确配置。Pandas是Python数据分析的核心库,通常与NumPy和Matplotlib一起使用。

安装依赖

可以通过pip或conda安装所需依赖:

pip install pandas numpy matplotlib

或者使用conda:

conda install pandas numpy matplotlib

初识Pandas

让我们从一个简单的NBA数据集开始探索Pandas的强大功能。

加载数据

首先下载并加载NBA历史比赛数据:

import pandas as pd

# 读取CSV文件
nba = pd.read_csv("nba_all_elo.csv")

数据概览

了解数据的基本信息:

# 查看数据类型
print(type(nba))  # <class 'pandas.core.frame.DataFrame'>

# 数据集大小
print(len(nba))  # 126314条记录
print(nba.shape)  # (126314, 23) 表示126314行23列

# 查看前几行数据
print(nba.head())

# 查看后几行数据
print(nba.tail())

数据展示设置

调整Pandas的显示选项以获得更好的查看体验:

# 显示所有列
pd.set_option("display.max.columns", None)

# 设置显示精度
pd.set_option("display.precision", 2)

深入了解数据

数据类型分析

使用.info()方法查看各列的数据类型和缺失值情况:

nba.info()

基本统计信息

.describe()方法提供数值列的统计摘要:

nba.describe()

对于非数值列:

import numpy as np
nba.describe(include=object)

数据探索实践

让我们进行一些实际的数据探索:

# 各球队比赛场次统计
print(nba["team_id"].value_counts())

# 各球队名称出现次数
print(nba["fran_id"].value_counts())

# 湖人队的不同球队ID统计
print(nba.loc[nba["fran_id"] == "Lakers", "team_id"].value_counts())

日期处理

将比赛日期转换为datetime类型并进行时间分析:

nba["date_played"] = pd.to_datetime(nba["date_game"])

# 明尼阿波利斯湖人队(MNL)的比赛时间范围
print(nba.loc[nba["team_id"] == "MNL", "date_played"].agg(("min", "max")))

Pandas数据结构详解

Series:Pandas的基础构建块

Series是Pandas中的一维数据结构:

revenues = pd.Series([5555, 7000, 1980])
print(revenues.values)  # 查看值数组
print(revenues.index)   # 查看索引

可以自定义索引:

city_revenues = pd.Series(
    [4200, 8000, 6500], index=["Amsterdam", "Toronto", "Tokyo"]
)

Series与Python数据结构的比较

Series与字典类似但功能更强大:

city_employee_count = pd.Series({"Amsterdam": 5, "Tokyo": 8})
print("Tokyo" in city_employee_count)  # True
print("New York" in city_employee_count)  # False

DataFrame:Pandas的核心数据结构

DataFrame是二维表格型数据结构:

city_data = pd.DataFrame(
    {"revenue": city_revenues, "employee_count": city_employee_count}
)

查看DataFrame的基本属性:

print(city_data.index)   # 行索引
print(city_data.columns) # 列名
print(city_data.values)  # 值数组

数据访问技巧

Series数据访问

有多种方式访问Series中的数据:

# 通过索引标签
print(city_revenues["Toronto"])  # 8000

# 通过位置
print(city_revenues[1])  # 8000
print(city_revenues[-1]) # 6500

# 切片操作
print(city_revenues[1:])
print(city_revenues["Toronto":])

使用.loc和.iloc

.loc基于标签,.iloc基于位置:

colors = pd.Series(
    ["red", "purple", "blue", "green", "yellow"], index=[1, 2, 3, 5, 8]
)

print(colors.loc[1])   # 'red' (标签为1的值)
print(colors.iloc[1])  # 'purple' (第二个位置的值)

print(colors.iloc[1:3])  # 位置1到2
print(colors.loc[3:8])   # 标签3到8

DataFrame数据访问

访问列数据:

print(city_data["revenue"])
print(city_data.revenue)  # 等效的简写形式

访问行数据:

print(city_data.loc["Amsterdam"])  # 通过标签
print(city_data.iloc[1])          # 通过位置

同时选择行和列:

print(city_data.loc["Amsterdam":"Tokyo", "revenue"])

实践练习

  1. 显示NBA数据集的最后3行
  2. 计算波士顿凯尔特人队在所有比赛中的总得分
  3. 显示NBA数据集的倒数第二行

通过这些基础操作,您已经掌握了使用Pandas进行数据探索的基本技能。Pandas的强大功能远不止于此,后续可以深入学习数据清洗、转换、分组聚合等高级操作。

登录后查看全文
热门项目推荐
相关项目推荐