文件读取与存储

  • 1 CSV
    • 1.1 read_csv
    • 1.2 to_csv
    • 1.3案例
  • 2 HDF5
    • 2.1 read_hdf与to_hdf
    • 2.2案例
  • 3 JSON
    • 3.1 read_json
    • 3.2 read_josn案例
    • 3.3 to_json
    • 3.4案例
  • 优先选择使用HDF5文件存储

我们的数据大部分存在于文件当中,因此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:指定重新读取的列名,列表形式

读取之前的股票的数据

# 读取文件,并且指定只获取'open', 'close'指标
data = pd.read_csv("./data/stock_day.csv", usecols=['open', 'close'])open    high    close
2018-02-27    23.53    25.88    24.16
2018-02-26    22.80    23.78    23.53
2018-02-23    22.88    23.37    22.82
2018-02-22    22.25    22.76    22.28
2018-02-14    21.49    21.99    21.92

1.2 to_csv

  • DataFrame.to_csv(path_or_buf =无,sep =’,’,列=无,标头=真,索引=真,模式=‘w’,编码=无)

    • path_or_buf:文件路径
    • sep:分隔符,默认用“,”替换
    • 列:选择需要的列索引
    • header:布尔值或字符串列表,默认为True,是否写进列索引值
    • index:是否写进行索引
    • 模式:‘w’:重组,'a’追加

1.3案例

保存’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:存储不会讲索引值变成一列数据
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:读取的键
    • 返回:所选对象
  • DataFrame.to_hdf(path_or_buf,key,* \ kwargs *)

2.2案例

读取文件

day_eps_ttm = pd.read_hdf("./data/stock_data/day/day_eps_ttm.h5")

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

需要安装表格模块避免不能读取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,预期的JSON字符串格式的指示。
      • ‘split’:像{index->​​ [index],columns-> [columns],data-> [values]}之类的字典

        • split将索引总结到索引,列名到列名,数据到数据。将三部分都分开了
      • ‘records’:类似于[{column-> value},…,{column-> value}]的列表
        • 记录以columns:values的形式输出
      • ‘index’:类似{index->​​ {column-> value}}的字典
        • index以index:{columns:values}…的形式输出
      • ‘columns’:类似{column-> { index- > value}}的字典,该格式
        • 列以columns:{index:values}的形式输出
      • ‘values’:仅是values数组
        • 直接输出值
    • lines:布尔值,默认为False
    • 按照每行读取json对象
    • typ:默认为’frame’,指定转换成的对象类型系列或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格式,行指定跟随行去变成一个样本
json_read = pd.read_json("./data/Sarcasm_Headlines_Dataset.json", orient="records", lines=True)

结果为:

3.3 to_json

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

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

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}...

优先选择使用HDF5文件存储

  • HDF5在存储的时候支持压缩,使用的方式是blosc,这个是速度驱动的也是pandas替代支持的
  • 使用压缩可以提磁盘优化,节省空间
  • HDF5还是跨平台的,可以轻松迁移到hadoop上面

Pandas之文件读取与存储相关推荐

  1. Pandas:文件读取、存储【读取:read_**()、写入:to_**()】【文件类型:csv、excel、json、HDF5】

    我们的数据大部分存在于文件当中,所以pandas会支持复杂的IO操作,pandas的API支持众多的文件格式,如CSV.SQL.XLS.JSON.HDF5. 注:最常用的HDF5和CSV文件 1 CS ...

  2. 机器学习3:——Pandas——3:文件读取和存储

    一.文件读取与存储 学习目标 目标 了解Pandas的几种文件读取存储操作 应用CSV方式和HDF方式实现文件的读取和存储 应用 实现股票数据的读取存储 我们的数据大部分存在于文件当中,所以panda ...

  3. pandas文件读取与存储

    pandas文件读取与存储 我们的数据大部分存在于文件当中,所以pandas会支持复杂的IO操作,pandas的API支持众多的文件格式,如CSV.SQL.XLS.JSON.HDF5. 注:最常用的H ...

  4. 学习笔记Spark(四)—— Spark编程基础(创建RDD、RDD算子、文件读取与存储)

    文章目录 一.创建RDD 1.1.启动Spark shell 1.2.创建RDD 1.2.1.从集合中创建RDD 1.2.2.从外部存储中创建RDD 任务1: 二.RDD算子 2.1.map与flat ...

  5. python:文件读取和存储

    文章目录 一.文件的打开.读取.加载 1.python内置函数:open()打开.f.read()读取 2.pandas库 3.numpy库 二.文件的写入.存储 1.python内置函数:f.wri ...

  6. 3-7 pandas数据的读取与存储

    数据分析工具pandas 7. 数据的读取与存储 7.1 读操作 7.2 写操作 7.3 JSON格式 7.4 分块读取大文件 Pandas是一个强大的分析结构化数据的工具集,基于NumPy构建,提供 ...

  7. pandas parquet文件读取pyarrow、feather文件保存与读取;requests 或wget下载图片文件

    **pandas读取文件填写绝对路径,相对路径可能出错读不了 安装 fastparquet库,需要安装python-snappy ,一直安装错误,所以使用了pyarrow pip install py ...

  8. 在Python中使用pandas进行文件读取和写入方法详解

    Pandas 是 Python 的一个功能强大且灵活的三方包,可处理标记和时间序列数据.还提供统计方法.启用绘图等功能.Pandas 的一项重要功能是能够编写和读取 Excel.CSV 和许多其他类型 ...

  9. php大文件读取和存储,php存储大文件思路

    这个似乎是没办法. 看这段: 在图片上传部分,其实能玩的花样很少,但是编写代码所消耗的时间最多.现在我们再假设一种情景,如果我们的图片服务器前端采用Nginx,上传功能 用PHP实现,需要写的代码很少 ...

最新文章

  1. C语言,C#,Java,JavaScript之强类型与弱类型
  2. linux远程脚本事例,ssh远程执行命令方法和Shell脚本实例
  3. 深度学习的非主流应用
  4. linux远程跳板机超时
  5. Discuz升级 Database Error : pre_common_syscache ADD PRIMARY KEY (cname)【解决办法】
  6. android或java timer声明
  7. Java配置文件的使用
  8. python点击屏幕_python实现鼠标自动点击屏幕
  9. 【用户】create_user_with_sshkey.sh
  10. javawebday30(验证码在客户端 用当前时间来请求下一张图片 VerifyCode代码)
  11. paip.手机电话本备份导入到pc管理attilax总结
  12. 汇编intel 8086/8088/80386 学习
  13. 局域网下两台电脑ping不通的问题
  14. linux下的/usr目录
  15. 大一时写的东西 哈哈~~~~~~~~~~~~
  16. eclipse没有Java EE透视图!
  17. linux解封ip,linux iptables禁IP与解封IP常用命令
  18. python如何安装pil库_Python安装PIL库
  19. 使用PaddleDetection自带脚本将自制labelme数据集转为coco格式
  20. php友情链接大于3换行,友情链接11大欺骗方法

热门文章

  1. VaR风险价值-Python版本
  2. springboot角色权限后台管理系统脚手架实战开发教程包含完整源码
  3. Linux IPC 进程间通信——消息队列message
  4. 2016职称计算机考试报名费,无锡2016年职称计算机考试报名费用
  5. python一张图-python 实现在一张图中绘制一个小的子图方法
  6. matlab图像处理图像的几种输出方法
  7. 化工热力学习题集及答案
  8. [bzoj 3252]攻略
  9. GPS接收机学习小记(二)
  10. html如何实现立体效果,在页面中怎么用css让图片有立体感的效果?(代码实测)...