【深耕 Python】Data Science with Python 数据科学(8)pandas数据结构:Series和DataFrame

写在前面

关于数据科学环境的建立,可以参考我的博客:

【深耕 Python】Data Science with Python 数据科学(1)环境搭建

往期数据科学博文:

【深耕 Python】Data Science with Python 数据科学(2)jupyter-lab和numpy数组

【深耕 Python】Data Science with Python 数据科学(3)Numpy 常量、函数和线性空间

【深耕 Python】Data Science with Python 数据科学(4)(书337页)练习题及解答

【深耕 Python】Data Science with Python 数据科学(5)Matplotlib可视化(1)

【深耕 Python】Data Science with Python 数据科学(6)Matplotlib可视化(2)

【深耕 Python】Data Science with Python 数据科学(7)书352页练习题

代码说明: 由于实机运行的原因,可能省略了某些导入(import)语句。

Jupyter 代码片段 1:定义简单的Series

python 复制代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

print(pd.Series([1, 2, 3, "foo", np.nan, "bar"]))
print()
print(pd.Series([1, 2, 3, "foo", np.nan, "bar"]).dropna())

运行结果:

Jupyter 代码片段 2:Series的索引、自定义索引

Series的索引支持自定义,可以通过索引访问各个成员、进行切片操作等。

python 复制代码
from numpy.random import default_rng

print(pd.Series([1, 2, 3, "foo", np.nan, "bar"]).index)
rng = default_rng()
print()
s = pd.Series(rng.standard_normal(5), index=["a", "b", "c", "d", "e"])
print(s)
print()
print(s[0])
print()
print(s[1:3])
print()
print(s["c"])
print()
print(s.keys())
print()
print(s.index)

运行结果:

Jupyter 代码片段 3:简单直方图的绘制

使用1000个标准正态分布的样本点,绘制直方图:

python 复制代码
s = pd.Series(rng.standard_normal(1000))
s.hist()
plt.show()

运行结果:

Jupyter 代码片段 4:DataFrame的构造、访问和映射

python 复制代码
from math import tau
from numpy.random import default_rng

rng = default_rng()
df = pd.DataFrame(
    {
        "Number": 1.0,
        "String": "foo",
        "Angles": np.linspace(0, tau, 5),
        "Random": pd.Series(rng.standard_normal(5)),
        "Timestamp": pd.Timestamp("20221020"),
        "Size": pd.Categorical(["tiny", "small", "mid", "big", "huge"])
    }
)

print(df)
print()
print(df["Size"])
print()
print(df["Random"].mean())
print()
print(df.describe())
print()
sizes = {"tiny": 4, "small": 8, "mid": 12, "big": 16, "huge": 24}
df["Size"].map(sizes)

运行结果:

参考文献 Reference

《Learn Enough Python to be Dangerous------Software Development, Flask Web Apps, and Beginning Data Science with Python》, Michael Hartl, Boston, Pearson, 2023.

相关推荐
OPEN-F10 分钟前
Python进阶教程:单元测试与代码质量
开发语言·python·单元测试
_Narcissus_30 分钟前
枚举和模拟算法笔记
c语言·数据结构·c++·笔记·算法·模拟·枚举
Logintern0930 分钟前
装饰器和洋葱模式的区分
开发语言·python·架构
冻柠檬飞冰走茶1 小时前
《数据结构实验指导-C++语言版》 在顺序表 list 中查找元素 x
开发语言·数据结构·c++·算法·list
Brilliantwxx1 小时前
【C++】 高阶数据结构图(1)并查集
开发语言·数据结构·c++
呆呆敲代码的小Y1 小时前
10 分钟搞懂 cua:开源 AI 操作电脑基础设施,附 Python 沙箱与 Agent 上手代码
人工智能·python·开源·ai agent·awesome·llm应用·cua
工具分享1 小时前
带店托管必用爆单AI选品,一人公司轻松掌握
人工智能·python
l1258651 小时前
# RAG低延迟架构设计:从5秒到500ms的优化全链路
数据库·人工智能·python·langchain
杨丰玮4181 小时前
从零手写Java飞机躲障碍游戏|Swing绘图、鼠标跟随、计时器碰撞检测实战(五)
java·python·游戏·游戏引擎·图形渲染·动画·贴图
frjc1 小时前
阿里云 ACK 环境 Arthas 在线调试指南
开发语言·python