【深耕 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.

相关推荐
孟健9 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞10 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽13 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程17 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪17 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook18 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python