🏆🏆🏆教程全知识点简介:1.机器学习常用科学计算库包括基础定位、目标。2. 人工智能概述涵盖人工智能应用场景、人工智能小案例、人工智能发展必备三要素、人工智能机器学习和深度学习。3. 机器学习概述包括机器学习工作流程、什么是机器学习、模型评估(回归模型评估、拟合)、Azure机器学习模型搭建、完整机器学习项目流程。4. 机器学习基础环境安装与使用包括Jupyter Notebook使用(一级标题、Jupyter Notebook中自动补全代码等相关功能拓展)。5. Matplotlib可视化涵盖Matplotlib HelloWorld(什么是Matplotlib、实现简单Matplotlib画图折线图、画出温度变化图、准备数据、创建画布、绘制折线图、显示图像、构造x轴刻度标签、修改坐标刻度显示、设置中文字体、设置正常显示符号、保存图片)、添加坐标轴刻度、添加网格显示、添加描述信息、图像保存、设置图形风格、常见图形绘制(常见图形种类意义、散点图绘制)。6. Numpy包括Numpy优势、N维数组ndarray(ndarray属性)、基本操作(生成数组方法、生成0和1数组、从现有数组生成、创建符合正态分布股某票涨跌幅数据)、数组间运算(数组与数的运算)。7. Pandas数据结构包括Series、DataFrame。8. 文件读取与存储涵盖CSV(read_csv)、HDF(read_hdf与to_hdf)、JSON(read_josn)。9. 高级处理数据离散化包括为什么要离散化、什么是数据离散化、股某票涨跌幅离散化(读取股某票数据、将股某票涨跌幅数据进行分组、股某票涨跌幅分组数据变成one_hot编码)、案例实现。


📚📚👉👉👉本站这篇博客:   https://blog.csdn.net/yinuo_432/article/details/150395426    中查看

📚📚👉👉👉本站这篇博客:   https://blog.csdn.net/yinuo_432/article/details/150472118    中查看

✨ 本教程项目亮点

🧠 知识体系完整:覆盖从基础原理、核心方法到高阶应用的全流程内容
💻 全技术链覆盖:完整前后端技术栈,涵盖开发必备技能
🚀 从零到实战:适合 0 基础入门到提升,循序渐进掌握核心能力
📚 丰富文档与代码示例:涵盖多种场景,可运行、可复用
🛠 工作与学习双参考:不仅适合系统化学习,更可作为日常开发中的查阅手册
🧩 模块化知识结构:按知识点分章节,便于快速定位和复习
📈 长期可用的技术积累:不止一次学习,而是能伴随工作与项目长期参考


🎯🎯🎯全教程总章节


🚀🚀🚀本篇主要内容

Pandas

学习目标

  • 了解Numpy与Pandas的不同
  • 说明Pandas的Series与Dataframe两种结构的区别
  • 了解Pandas的MultiIndex与panel结构
  • 应用Pandas实现基本数据操作
  • 应用Pandas实现数据的合并
  • 应用crosstab和pivot_table实现交叉表与透视表
  • 应用groupby和聚合函数实现数据的分组与聚合
  • 了解Pandas的plot画图功能
  • 应用Pandas实现数据的读取和存储

5.6 文件读取与存储

学习目标

  • 目标

  • 了解Pandas的几种文件读取存储操作

  • 应用CSV方式、HDF方式和json方式实现文件的读取和存储

的数据大部分存在于文件当中,所以pandas会支持复杂的IO操作,pandas的API支持众多的文件格式,如CSV、SQL、XLS、JSON、HDF5。

注:最常用的HDF5和CSV文件

1 CSV

1.1 read_csv

  • pandas.read_csv(filepath_or_buffer, sep =',', usecols )

  • filepath_or_buffer:文件路径

  • sep :分隔符,默认用","隔开
  • usecols:指定读取的列名,列表形式

  • 举例:读取之前的股某票的数据

# 读取文件,并且指定只获取'open', 'close'指标


data = pd.read_csv("./data/stock_day.csv", usecols=['open', 'close'])

            open    close
2018-02-27    23.53    24.16
2018-02-26    22.80    23.53
2018-02-23    22.88    22.82
2018-02-22    22.25    22.28
2018-02-14    21.49    21.92

1.2 to_csv

  • DataFrame.to_csv(path_or_buf=None, sep=', ’, columns=None, header=True, index=True, mode='w', encoding=None)

  • path_or_buf :文件路径

  • sep :分隔符,默认用","隔开
  • columns :选择需要的列索引
  • header :boolean or list of string, default True,是否写进列索引值
  • index:是否写进行索引
  • mode:'w':重写, 'a' 追加

  • 举例:保存读取出来的股某票数据

  • 保存'open'列的数据,然后读取查看结果

# 选取10行数据保存,便于观察数据


data[:10].to_csv("./data/test.csv", columns=['open'])
# 读取,查看结果


pd.read_csv("./data/test.csv")

     Unnamed: 0    open
0    2018-02-27    23.53
1    2018-02-26    22.80
2    2018-02-23    22.88
3    2018-02-22    22.25
4    2018-02-14    21.49
5    2018-02-13    21.40
6    2018-02-12    20.70
7    2018-02-09    21.20
8    2018-02-08    21.79
9    2018-02-07    22.69

会发现将索引存入到文件当中,变成单独的一列数据。如果需要删除,可以指定index参数,删除原来的文件,重新保存一次。

# index:存储不会讲索引值变成一列数据


data[:10].to_csv("./data/test.csv", columns=['open'], index=False)

2 HDF5

2.1 read_hdf与to_hdf

HDF5文件的读取和存储需要指定一个键,值为要存储的DataFrame

  • pandas.read_hdf(path_or_buf,key =None,** kwargs)

从h5文件当中读取数据

  • path_or_buffer:文件路径
  • key:读取的键
  • return:Theselected object

  • DataFrame.to_hdf(path_or_buf, key, **kwargs)

2.2 案例

  • 读取文件
day_close = pd.read_hdf("./data/day_close.h5")

如果读取的时候出现以下错误

需要安装安装tables模块避免不能读取HDF5文件

pip install tables

  • 存储文件
day_close.to_hdf("./data/test.h5", key="day_close")

python-dateutil 文档

再次读取的时候, 需要指定键的名字

new_close = pd.read_hdf("./data/test.h5", key="day_close")

注意:优先选择使用HDF5文件存储

  • HDF5在存储的时候支持压缩,使用的方式是blosc,这个是速度最快的也是pandas默认支持的
  • 使用压缩可以提磁盘利用率,节省空间
  • HDF5还是跨平台的,可以轻松迁移到hadoop 上面

3 JSON

JSON是 常用的一种数据交换格式,前面在前后端的交互经常用到,也会在存储的时候选择这种格式。所以 需要知道Pandas如何进行读取和存储JSON格式。

3.1 read_json

  • pandas.read_json(path_or_buf=None, orient=None, typ='frame', lines=False)

  • 将JSON格式准换成默认的Pandas DataFrame格式

  • orient : string,Indication of expected JSON string format.

    • 'split' : dict like {index -> [index], columns -> [columns], data -> [values]}

      • split 将索引总结到索引,列名到列名,数据到数据。将三部分都分开了
    • 'records' : list like [{column -> value}, ... , {column -> value}]

      • records 以columns:values的形式输出
    • 'index' : dict like {index -> {column -> value}}

      • index 以index:{columns:values}...的形式输出
    • 'columns' : dict like {column -> {index -> value}},默认该格式

      • colums 以columns:{index:values}的形式输出
    • 'values' : just the values array

      • values 直接输出值
  • lines : boolean, default False

    • 按照每行读取json对象
  • typ : default ‘frame’, 指定转换成的对象类型series或者dataframe

3.2 read_josn 案例

cryptography 文档

  • 数据介绍

这里使用一个新闻标题讽刺数据集,格式为json。is_sarcastic:1讽刺的,否则为0;headline:新闻报道的标题;article_link:链接到原始新闻文章。存储格式为:

{"article_link": "https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5", "headline": "former versace store clerk sues over secret 'black code' for minority shoppers", "is_sarcastic": 0}
{"article_link": "https://www.huffingtonpost.com/entry/roseanne-revival-review_us_5ab3a497e4b054d118e04365", "headline": "the 'roseanne' revival catches up to our thorny political mood, for better and worse", "is_sarcastic": 0}
  • 读取

orient指定存储的json格式,lines指定按照行去变成一个样本

json_read = pd.read_json("./data/Sarcasm_Headlines_Dataset.json", orient="records", lines=True)

PyTorch 文档

结果为:

3.3 to_json

  • DataFrame.to_json(path_or_buf=None, orient=None, lines=False)

  • 将Pandas 对象存储为json格式

  • path_or_buf=None:文件地址
  • orient:存储的json形式,{‘split’,’records’,’index’,’columns’,’values’}
  • lines:一个对象存储为一行

3.4 案例

  • 存储文件
json_read.to_json("./data/test.json", orient='records')

结果

[{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/versace-black-code_us_5861fbefe4b0de3a08f600d5","headline":"former versace store clerk sues over secret 'black code' for minority shoppers","is_sarcastic":0},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/roseanne-revival-review_us_5ab3a497e4b054d118e04365","headline":"the 'roseanne' revival catches up to our thorny political mood, for better and worse","is_sarcastic":0},{"article_link":"https:\/\/local.theonion.com\/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697","headline":"mom starting to fear son's web series closest thing she will have to grandchild","is_sarcastic":1},{"article_link":"https:\/\/politics.theonion.com\/boehner-just-wants-wife-to-listen-not-come-up-with-alt-1819574302","headline":"boehner just wants wife to listen, not come up with alternative debt-reduction ideas","is_sarcastic":1},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/jk-rowling-wishes-snape-happy-birthday_us_569117c4e4b0cad15e64fdcb","headline":"j.k. rowling wishes snape happy birthday in the most magical way","is_sarcastic":0},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/advancing-the-worlds-women_b_6810038.html","headline":"advancing the world's women","is_sarcastic":0},....]
  • 修改lines参数为True
json_read.to_json("./data/test.json", orient='records', lines=True)

结果

{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/versace-black-code_us_5861fbefe4b0de3a08f600d5","headline":"former versace store clerk sues over secret 'black code' for minority shoppers","is_sarcastic":0}
{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/roseanne-revival-review_us_5ab3a497e4b054d118e04365","headline":"the 'roseanne' revival catches up to our thorny political mood, for better and worse","is_sarcastic":0}
{"article_link":"https:\/\/local.theonion.com\/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697","headline":"mom starting to fear son's web series closest thing she will have to grandchild","is_sarcastic":1}
{"article_link":"https:\/\/politics.theonion.com\/boehner-just-wants-wife-to-listen-not-come-up-with-alt-1819574302","headline":"boehner just wants wife to listen, not come up with alternative debt-reduction ideas","is_sarcastic":1}
{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/jk-rowling-wishes-snape-happy-birthday_us_569117c4e4b0cad15e64fdcb","headline":"j.k. rowling wishes snape happy birthday in the most magical way","is_sarcastic":0}...

4 小结

  • pandas的CSV、HDF5、JSON文件的读取【知道】

  • 对象.read_**()

  • 对象.to_**()

5.7 高级处理-缺失值处理

学习目标

  • 目标

  • 应用isnull判断是否有缺失数据NaN

  • 应用fillna实现缺失值的填充
  • 应用dropna实现缺失值的删除
  • 应用replace实现数据的替换

1 如何处理nan

  • 获取缺失值的标记方式(NaN或者其他标记方式)

  • 如果缺失值的标记方式是NaN

  • 判断数据中是否包含NaN:

    • pd.isnull(df),
    • pd.notnull(df)
  • 存在缺失值nan:

    • 1、删除存在缺失值的:dropna(axis='rows')

      • 注:不会修改原数据,需要接受返回值
    • 2、替换缺失值:fillna(value, inplace=True)

      • value:替换成的值
      • inplace:True:会修改原数据,False:不替换修改原数据,生成新的对象
  • 如果缺失值没有使用NaN标记,比如使用"?"

  • 先替换‘?’为np.nan,然后继续处理

2 电影数据的缺失值处理

  • 电影数据文件获取
# 读取电影数据


movie = pd.read_csv("./data/IMDB-Movie-Data.csv")

2.1 判断缺失值是否存在

  • pd.notnull()
pd.notnull(movie)
Rank    Title    Genre    Description    Director    Actors    Year    Runtime (Minutes)    Rating    Votes    Revenue (Millions)    Metascore
0    True    True    True    True    True    True    True    True    True    True    True    True
1    True    True    True    True    True    True    True    True    True    True    True    True
2    True    True    True    True    True    True    True    True    True    True    True    True
3    True    True    True    True    True    True    True    True    True    True    True    True
4    True    True    True    True    True    True    True    True    True    True    True    True
5    True    True    True    True    True    True    True    True    True    True    True    True
6    True    True    True    True    True    True    True    True    True    True    True    True
7    True    True    True    True    True    True    True    True    True    True    False    True
np.all(pd.notnull(movie))
  • pd.isnull()

BeautifulSoup 文档

2.2 存在缺失值nan,并且是np.nan

  • 1、删除

pandas删除缺失值,使用dropna的前提是,缺失值的类型必须是np.nan

# 不修改原数据


movie.dropna()



# 可以定义新的变量接受或者用原来的变量名


data = movie.dropna()
  • 2、替换缺失值
# 替换存在缺失值的样本的两列




# 替换填充平均值,中位数




# movie['Revenue (Millions)'].fillna(movie['Revenue (Millions)'].mean(), inplace=True)

替换所有缺失值:

for i in movie.columns:
    if np.all(pd.notnull(movie[i])) == False:
        print(i)
        movie[i].fillna(movie[

🚀✨ (未完待续)项目系列下一章

📚下一篇 将进入更精彩的环节! 🔔 记得收藏 & 关注,第一时间获取更新! 🍅 一起见证整个系列逐步成型的全过程。

Logo

更多推荐