pandas文件读取与存储


我们的数据大部分存在于文件当中,所以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")

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

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

  • 数据介绍

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

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

    • 对象.read_**()
    • 对象.to_**()

pandas文件读取与存储相关推荐

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

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

  2. Pandas之文件读取与存储

    文件读取与存储 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. ...

  3. 学习笔记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 ...

  4. Pandas 文件读取和导出

    Pandas 文件读取和导出 更新时间:2020-12-28 00:16:20标签:pandas io 说明 Pandas 中文教程修订中,欢迎加微信 sinbam 提供建议.纠错.催更.查看更新日志 ...

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

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

  6. python:文件读取和存储

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

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

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

  8. php大文件读取和存储,使用PHP读取和解析大文件实战

    21CTO导读:在现在这篇文章中,我们将一起学习处理PHP中的大文件,避免因内存限制而无法使用的方法. 如果你想用PHP处理大文件,PHP提供了一些普通的PHP函数,比如file_get_conten ...

  9. 【Python百日基础系列】Day12 - Pandas 数据读取与存储

    文章目录 一.官网用户指南 二.数据读取 2.1 查看当前目录 2.2 最简单的读取csv和excel文件 2.3 读取前20行 2.4 跳过前20行 2.5 读取全部偶数行/奇数行 2.6 按列号和 ...

最新文章

  1. 中判断字符串是否为空_java中的数字以及如何判断字符串是不是数字
  2. linux --- 高级指令
  3. 【CodeForces - 144D】Missile Silos(单源最短路,枚举中间边,枚举情况可能性)
  4. 【PKUSC2019】线弦图【计数】【树形DP】【分治FFT】
  5. 数学家告诉你什么时候结束单身?!
  6. Web中常用字体介绍(转)
  7. php高德地图坐标在多边形,多边形的绘制和编辑
  8. 【多线程】线程的生命周期
  9. Mac上的UML建模工具
  10. 【5G/4G】ZUC算法源码介绍
  11. android剪贴板清空,如何访问和清除Android手机上的剪贴板
  12. python中element什么意思_什么是Python中等效的’nth_element’函数?
  13. 把txt 转换成CHM的目录或Index
  14. l1约束比l2约束更容易获得稀疏解
  15. 神级操作丨用 Python 将微信热文转换成Word文档
  16. Loadrunner11.00破解方法
  17. [小白系列]利用echarts或者pyecharts来实现高端大气上档次的可视化
  18. 〖小狼毫〗配置后的效果
  19. 创建微信机器人和女朋友聊天_创建聊天机器人
  20. 跳跃表原理及redis跳跃表的应用

热门文章

  1. cursor :ponter;
  2. JAVA删除字符串固定下标的字串
  3. 图灵奖得主John Hopcroft推荐的这本强化学习入门书
  4. 开源项目-仓库管理系统
  5. OpenCV-Python实现绿幕图像抠图
  6. 电脑控制手机-帮你在电脑上录制手机屏幕和声音
  7. 伪元素 内容 content 符号,图标
  8. 信息系统项目管理师第三版 pdf可编辑_信息系统项目管理师备考资料-第三版(3)...
  9. java在退出前释放资源,【java】手动释放资源问题
  10. 海康终端服务器5012a,TS-5012-F终端服务器-HikvisionUSA解析.pdf