标签(空格分隔): Python


读入读出通常可以划分为几个大类:读取文本文件和其他更高效的磁盘存储格式,加载数据库中的数据,利用Web API操作网络资源。

读写文本格式的数据

pandas提供了一些用于将表格型数据读取为DataFrame对象的函数,如下表所示:

函数 说明
read_csv 从文件、URL、文件型对象中加载带分隔符的数据。默认分隔符为,
read_table 从文件、URL、文件型对象中加载带分隔符的数据,默认的分隔符为制表符"\t"
read_fwf 读取定宽列格式数据 -- 木有分隔符的
read_clipboard 读取剪贴板中的数据,可以看做read_table的剪贴板。将网页转换为表格时很有用

for example:

In[]: import pandas as pd
In[]: df = pd.read_csv('ex1.csv') # ''内写入文件所在的详细目录
In[]: df = pd.read_table('ex1.csv', sep = ',') # 或者使用table并指定分隔符 # 当你要读入的文件没有标题行时:
In[]: df = pd.read_csv('ex2.csv', header = None) # 让pandas为其分配默认的列名
In[]: df = pd.read_csv('ex2.csv', names = ['a','b','c','d','message']) # 自己定义标题行
In [8]: names = ['a','b','c','d','message'] # 让其中的某列作为列索引
In [9]: pd.read_csv('ex2.csv', names = names, index_col = 'message')
Out[9]:
a b c d
message
hello 1 2 3 4
world 5 6 7 8
foo 9 10 11 12
In[]: pd.read_csv('ex4.csv', skiprows = [0, 2, 3]) # 略过第0,2,3行不读取 # 用一个字典为各列指定不同的NA标记值
In[]: patterns = {'message':['foo', 'NA'], 'something':['two']}
In[]: pd.read_csv('ex5.csv', na_values=patterns)
  • read_csv/read_table函数的参数
参数 说明
path 表示文件系统位置、URL、文件型对象的字符串
sep/delimiter 用于对行中各字段进行拆分的字符序列或正则表达式
header 用作列名的行号。如果没有header行就应该设置为None
index_col 用作行索引的列编号或列名,可以是单个名称/数字或由多个名称/数字组成的列表
names 用于结果的列名列表,结合header = None
skiprows 需要忽略的行数
na_values 一组用于替换NA的值
comment 用于将注释信息从行尾拆分出去的字符
parse_dates 尝试将数据解析为日期
nrows 需要读取的行数
skip_footer 需要忽略的行数

逐块读取文本文件

In[]: pd.read_csv('ex6.csv', nrows=5)

将数据写出到文本

In[]: data = pd.read_csv('ex5.csv')
In[]: data.to_csv('out.csv') # 将data中的数据写出到当前目录中的out.csv中
In[]: data.to_csv(sys.stdout, sep='|') # 打印到屏幕
In[]: data.to_csv(sys.stdout, na_rep='NULL') # 空字符处显示为NULL
In[]: data.to_csv(sys.stdout, index=False, header=False) # 禁用行和列的标签
In[]: data.to_csv(sys.stdout, index=False, cols=['a', 'b', 'c']) # 按照指定的顺序显示列 # Series中的to_csv方法
In [39]: dates = pd.date_range('1/1/2000', periods = 7) In [40]: dates
Out[40]:
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07'], dtype='datetime64[ns]', freq='D')
In [45]: ts = Series(np.arange(7), index = dates) In [46]: ts
Out[46]:
2000-01-01 0
2000-01-02 1
2000-01-03 2
2000-01-04 3
2000-01-05 4
2000-01-06 5
2000-01-07 6
Freq: D, dtype: int64
In [47]: ts.to_csv('tseries.csv') In [48]: cat tseries.csv
2000-01-01,0
2000-01-02,1
2000-01-03,2
2000-01-04,3
2000-01-05,4
2000-01-06,5
2000-01-07,6 In[]: Series.from_csv('tseries.csv',parse_dates = False) # 从文件中读入到Series

手工处理分隔符

In [50]: cat ex7.csv
"a","b","c"
"1","2","3"
"1","2","3","4" In [51]: import csv
In [52]: f = open('ex7.csv')
In [53]: reader = csv.reader(f)
In [54]: for line in reader:
...: print line
...:
['a', 'b', 'c']
['1', '2', '3']
['1', '2', '3', '4'] # 可以对数据做一些处理
In[]: lines = list(csv.reader(open('ex7.csv')))
In[]: header, values = lines[0], lines[1:]
In[]: data_dict = {h:v for h,v in zip(header, zip(*values))}
  • CSV语支选项
参数 说明
delimiter 用于分割字段的单字符字符串,默认为','
lineterminator 用于写操作的行结束符,默认为'\r\n'。读操作将忽略此选项
quotechar 用于带有特殊字符的字段的引用符号,默认为'"'

JSON数据

JSON(JavaScript Object Notation)已经成为通过HTTP请求在Web浏览器和其他应用程序之间发送数据的标准格式之一。

import json
In [65]: obj = """{"name":"Wes", "places_lived":["United States", "Spain", "Germany"], "pet":nu
...: ll, "siblings":[{"name":"Scott","age":25,"pet":"Zuko"},{"name":"Katy","age":33,"pet":"
...: Cisco"}]}"""
In [68]: res = json.loads(obj) # 将JSON字符串转换为Python形式 In [69]: res
Out[69]:
{u'name': u'Wes',
u'pet': None,
u'places_lived': [u'United States', u'Spain', u'Germany'],
u'siblings': [{u'age': 25, u'name': u'Scott', u'pet': u'Zuko'},
{u'age': 33, u'name': u'Katy', u'pet': u'Cisco'}]} # 将Python转换为json
In [71]: asjson = json.dumps(res)
In [72]: asjson
Out[72]: '{"pet": null, "siblings": [{"pet": "Zuko", "age": 25, "name": "Scott"}, {"pet": "Cisco", "age": 33, "name": "Katy"}], "name": "Wes", "places_lived": ["United States", "Spain", "Germany"]}' In[]: data = DataFrame(res['siblings'], columns=['name', 'age'])
In [75]: data
Out[75]:
name age
0 Scott 25
1 Katy 33

使用HTML和Web API

import requests
In[]: url = 'http://www.baidu.com'
In[]: resp = requests.get(url)
In[]: import json
In[]: data = json.loads(resp.text) # Response对象的text属性含有GET请求的内容,大多返回JSON对象,加载到Python对象中
In[]: data.keys()

使用数据库

In[]: import sqlite3
In[]: query = """create table test(a varchar(20), b varchar(20), c real, d integer);"""
In[]: con = sqlite3.connect(':memory:') # 连接数据库
In[]: con.execute(query)
In[]: con.commit() In[]: data = [('Atlanta', 'Georgia', 1.25, 6), ('Tall', 'Flor', 2.6, 3), ('Saca', 'Calif', 1.7, 5)]
In[]: stmt = "insert into test values(?, ?, ?, ?)" In[]: con.execute(stmt, data)
In[]: con.commit() In[]: datas = con.execute('select * from test')
In[]: lines = datas.fetchall() # 从表中读取数据,将返回一个元祖列表
In[]: datas.description # 获得列名
In[]: DataFrame(rows, columns=zip(*datas.description)[0]) In[]: import pandas.io.sql as sql
In[]: sql.read_frame('select * from test', con) # 传入sql语句和连接对象

Python -- 数据加载、存储与文件格式的更多相关文章

  1. 利用python进行数据分析之数据加载存储与文件格式

    在开始学习之前,我们需要安装pandas模块.由于我安装的python的版本是2.7,故我们在https://pypi.python.org/pypi/pandas/0.16.2/#downloads ...

  2. python多种格式数据加载、处理与存储

    多种格式数据加载.处理与存储 实际的场景中,我们会在不同的地方遇到各种不同的数据格式(比如大家熟悉的csv与txt,比如网页HTML格式,比如XML格式),我们来一起看看python如何和这些格式的数 ...

  3. Python之pandas数据加载、存储

    Python之pandas数据加载.存储 0. 输入与输出大致可分为三类: 0.1 读取文本文件和其他更好效的磁盘存储格式 2.2 使用数据库中的数据 0.3 利用Web API操作网络资源 1. 读 ...

  4. 利用python进行数据加载和存储

    1.文本文件 (1)pd.read_csv加载分隔符为逗号的数据:pd.read_table从文件.URL.文件型对象中加载带分隔符的数据.默认为制表符.(加载为DataFrame结构) 参数name ...

  5. python数据分析笔记——数据加载与整理]

    [ python数据分析笔记——数据加载与整理] https://mp.weixin.qq.com/s?__biz=MjM5MDM3Nzg0NA==&mid=2651588899&id ...

  6. arcgis python 使用光标和内存中的要素类将数据加载到要素集 学习:http://zhihu.esrichina.com.cn/article/634

    学习:http://zhihu.esrichina.com.cn/article/634使用光标和内存中的要素类将数据加载到要素集 import arcpy arcpy.env.overwriteOu ...

  7. MPP 二、Greenplum数据加载

    Loading external data into greenplum database table using different ways... Greenplum 有常规的COPY加载方法,有 ...

  8. 科学计算三维可视化---TVTK入门(数据加载)

    一:数据加载 大多数可视化应用的数据并非是在TVTK库中构建的,很多都是通过接口读取外部数据文件 (一)使用vtkSTLReader来读取外部文件 .stl 文件是在计算机图形应用系统中,用于表示三角 ...

  9. [源码解析] PyTorch 分布式(1) --- 数据加载之DistributedSampler

    [源码解析] PyTorch 分布式(1) --- 数据加载之DistributedSampler 目录 [源码解析] PyTorch 分布式(1) --- 数据加载之DistributedSampl ...

随机推荐

  1. vim - line

    copy complete current line: yy replace a char (e.g. comma) to new line: %s/,/\r/g

  2. xargs -I

    xargs  -i 参数或者-I参数配合{}即可进行文件的操作.   -I replace-str              Replace  occurrences  of  replace-str ...

  3. NGINX、PHP-FPM开机自动启动

    NGINX SHELL脚本   放到/etc/init.d/下取名nginx #!/bin/sh # # nginx - this script starts and stops the nginx ...

  4. 网页3D引擎“Babylon.JS”入门教程翻译总结

    使用三个月的业余时间把官方教程的入门部分译为中文并上传到github,在下一步编程前做一个总结. 历程: 最早接触游戏编程是在大三下学期,用汇编语言和实验室里的单片机.触摸屏.电机(提供声效)编的打地 ...

  5. Leetcode: Sentence Screen Fitting

    Given a rows x cols screen and a sentence represented by a list of words, find how many times the gi ...

  6. sql要点

    oracle 并操作 union  自动去除重复    如果想保留重复,需要使用union all 交操作intersect  自动去除重复    如果想保留重复,需要使用intersect all ...

  7. HDU 1880 魔咒词典(字符串哈希)

    题目链接 Problem Description 哈利波特在魔法学校的必修课之一就是学习魔咒.据说魔法世界有100000种不同的魔咒,哈利很难全部记住,但是为了对抗强敌,他必须在危急时刻能够调用任何一 ...

  8. Coins

    Description Whuacmers use coins.They have coins of value A1,A2,A3...An Silverland dollar. One day Hi ...

  9. Visual Studio配色方案

    Eclipse开源工具和VS在诸多方面真的是差距非常大,无奈Java编程,使用VS非常麻烦.所以只能选择Eclipse 但是Eclipse的系统配色,又实在是不舒服,于是抽时间,从VS上抠了一份默认的 ...

  10. $.Ajax({});方法使用 返回json格式 string格式

    //Json格式 $.ajax({ url: url + "?action=Save1", type: "post", dataType: "json ...