学习目标

  • 目标

    • 了解Pandas的几种文件读取存储操作
    • 应用CSV方式和HDF方式实现文件的读取和存储
  • 应用
    • 实现股票数据的读取存储

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

注:最常用的HDF5和CSV文件

1 CSV

1.1 read_csv

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

    • filepath_or_buffer:文件路径
    • usecols:指定读取的列名,列表形式

读取之前的股票的数据

# 读取文件,并且指定只获取'最高价', '最低价'指标
data = pd.read_csv("./600690.csv", usecols=['最高价', '最低价'])

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 :string or file handle, default None
    • sep :character, default ‘,’
    • columns :sequence, optional
    • mode:'w':重写, 'a' 追加
    • index:是否写进行索引
    • header :boolean or list of string, default True,是否写进列索引值

1.3 案例

  • 保存'open'列的数据
# 选取10行数据保存,便于观察数据
data[:10].to_csv("./test.csv", columns=['最高价'])
  • 读取,查看结果
pd.read_csv("./test.csv")

注意文件编码为UTF-8

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

# index:存储不会讲索引值变成一列数据
data[:10].to_csv("./test.csv", columns=['最高价'], 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_eps_ttm = pd.read_hdf("./data/test.h5")

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

"No module named 'tables' " problem importing

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

pip install tables
  • 存储文件
day_eps_ttm.to_hdf("./data/test.h5", key="day_eps_ttm")

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

new_eps = pd.read_hdf("./data/test.h5", key="day_eps_ttm")

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 案例

  • 数据介绍

这里使用一个新闻标题讽刺数据集,格式为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)

结果为:

3.3 to_json

  • DataFrame.to_json(path_or_buf=Noneorient=Nonelines=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 拓展

优先选择使用HDF5文件存储

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

5 小结

  • pandas的CSV、HDF5、JSON文件的读取

Python数据分析——Pandas(5)相关推荐

  1. Python数据分析pandas之分组统计透视表

    Python数据分析pandas之分组统计透视表 数据聚合统计 Padans里的聚合统计即是应用分组的方法对数据框进行聚合统计,常见的有min(最小).max(最大).avg(平均值).sum(求和) ...

  2. Python数据分析pandas之数据拼接与连接

    Python数据分析pandas之数据拼接与连接 数据拼接处理 数据拼接处理指的是numpy.pandas里对数据的拼接.连接.合并等多种方法的概称.有时我们处理的数据会分很多步骤,而中间或者最终的结 ...

  3. Python数据分析pandas之dataframe初识

    Python数据分析pandas之dataframe初识 声明与简介 pandas是一个基于python的.快速的.高效.灵活.易用的开源的数据处理.分析包(工具)..pandas构建在numpy之上 ...

  4. Python数据分析pandas之series初识

    Python数据分析pandas之series初识 声明与简介 pandas是一个基于python的.快速的.高效.灵活.易用的开源的数据处理.分析包(工具)..pandas构建在numpy之上,它通 ...

  5. Python数据分析pandas之多层高维索引

    Python数据分析pandas之多层高维索引 DataFrame多层索引 多层索引简介 众所周知Pandas的Series和DataFrame存放的是一维和二维数组,那么想存放多维数组就得通过多层索 ...

  6. Python数据分析——Pandas基础:dt.datetime与pivot_table()数据透视表

    系列文章目录 Chapter 1:创建与探索DF.排序.子集化:Python数据分析--Pandas基础入门+代码(一) Chapter 2:聚合函数,groupby,统计分析:Python数据分析- ...

  7. Python数据分析pandas入门(一)------十分钟入门pandas

    Python数据分析基础 一.导入常用库 二.创建对象 三.查看数据 四.选取 五.通过标签选取 六.通过位置选取 七.布尔索引 八.赋值 九.缺失值处理 十.运算与统计 十一.Apply函数的作用 ...

  8. Python数据分析pandas入门练习题(四)

    Python数据分析基础 Preparation Exercise 1 - Filtering and Sorting Data Step 1. Import the necessary librar ...

  9. 【学习笔记】python数据分析-Pandas

    目录 pandas数据结构 创建Series数据 创建DataFrame数据 pandas的索引操作 重新索引 更换索引 索引选取 选取行 选取列 布尔选择 pandas的增删改 增加行或列 删除行或 ...

  10. python数据分析-pandas学习

    文章目录 一.pandas环境的搭建 1.pandas 简介 2.pandas安装和调用 二.pandas学习 1.pandas简介 2.pandas学习资源 3.pandas核心数据结构 4.Ser ...

最新文章

  1. tomcat部署下的web项目网页更改不能自动刷新
  2. Dropbox 的用户付费账户降级策略
  3. HyperLedger Fabric Introduction——区块链超级账本介绍
  4. 科幻作文计算机,种子科幻作文
  5. 云原生时代,Java还是Go?
  6. 几篇关于Hadoop+Hive数据仓库的入门文章
  7. 简单存取款机的实现---控制输入变量的规则
  8. 背包——变向背包(hdu2546,1114,1203,2189)
  9. NB-IOT物联网平台是如何工作的
  10. 山海镜花vivo服务器微信号,山海镜花初始号怎么刷
  11. 【游戏】基于matlab GUI可调电扇设计【含Matlab源码 1110期】
  12. 镜头像差之二——色差
  13. matlab算方差std,MATLAB 方差函数 var std
  14. word2Vec基础背景知识
  15. 浅谈利用javascript实现gb2312编码。
  16. NextCloud前端支持播放mov文件
  17. 1.js基础01-计算机基础
  18. NS3入门:第一个程序first.cc
  19. 睡眠不好怎么办?提升睡眠质量的小妙招
  20. 关于我用过的机械键盘

热门文章

  1. 2020机械员-通用基础(机械员)模拟考试题及机械员-通用基础(机械员)作业考试题库
  2. markdown 模板2
  3. 35岁程序员职业危机?那45-50岁的程序员都在干什么?
  4. PHP函数集合-一揽子方案
  5. 实现米思齐按键控制LED
  6. 实现米思齐按键控制LED灯
  7. 根据关键字位置为PDF添加文本和图片
  8. 项目管理之中高级管理(成本管理)
  9. 浪潮NF5280M5服务器做RAID装windows server2019系统保姆级教学
  10. 利用计算机创作小说,小说写作有几个套路? 计算机答案:6个