0%

利用Python进行数据分析(6):数据加载、存储与文件格式

利用Python进行数据分析》读书笔记。
第6章:数据加载、存储与文件格式。

利用Python进行数据分析》读书笔记。

第6章: 数据加载、存储与文件格式

所有用到的数据可以从作者的 github下载。

%pylab inline
import pandas as pd
from pandas import Series, DataFrame

from __future__ import division
from numpy.random import randn
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
np.random.seed(12345)
plt.rc('figure', figsize=(10, 6))


np.set_printoptions(precision=4)
Populating the interactive namespace from numpy and matplotlib

读写文本文件

读取各种格式

pandas读取文件的常用函数:

  • read_csv(): 读取逗号分隔的文本
  • read_table(): 读取 Tab 分隔的文本
  • read_fwf(): 读取固定宽度文本
  • read_clipboard(): 读取剪切板

pandas读取文件会自动推断数据类型,不用指定。

# 标准格式
!cat data/ch06/ex1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
df = pd.read_csv('data/ch06/ex1.csv')
df
Out[5]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
#  指定分隔符
pd.read_table('data/ch06/ex1.csv', sep=',')
Out[20]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
# 无标题行数据
!cat data/ch06/ex2.csv
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
pd.read_csv('data/ch06/ex2.csv', header=None)
Out[22]:
0 1 2 3 4
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
#  可以指定标题
pd.read_csv('data/ch06/ex2.csv', names=['a', 'b', 'c', 'd', 'message'])
Out[23]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
# 指定标题和索引
names = ['a', 'b', 'c', 'd', 'message']
pd.read_csv('data/ch06/ex2.csv', names=names, index_col='message')
Out[24]:
a b c d
message
hello 1 2 3 4
world 5 6 7 8
foo 9 10 11 12
# 指定层次化索引
!cat data/ch06/csv_mindex.csv
parsed = pd.read_csv('data/ch06/csv_mindex.csv', index_col=['key1', 'key2'])
parsed
key1,key2,value1,value2
one,a,1,2
one,b,3,4
one,c,5,6
one,d,7,8
two,a,9,10
two,b,11,12
two,c,13,14
two,d,15,16
Out[25]:
value1 value2
key1 key2
one a 1 2
b 3 4
c 5 6
d 7 8
two a 9 10
b 11 12
c 13 14
d 15 16
# 非标准分隔符
list(open('data/ch06/ex3.txt'))
Out[26]:
['            A         B         C\n',
 'aaa -0.264438 -1.026059 -0.619500\n',
 'bbb  0.927272  0.302904 -0.032399\n',
 'ccc -0.264273 -0.386314 -0.217601\n',
 'ddd -0.871858 -0.348382  1.100491\n']
# 可以用正则表达式作为分隔符
result = pd.read_table('data/ch06/ex3.txt', sep='\s+')
result
Out[27]:
A B C
aaa -0.264438 -1.026059 -0.619500
bbb 0.927272 0.302904 -0.032399
ccc -0.264273 -0.386314 -0.217601
ddd -0.871858 -0.348382 1.100491
# 跳过一些行
!cat data/ch06/ex4.csv
pd.read_csv('data/ch06/ex4.csv', skiprows=[0, 2, 3])
# hey!
a,b,c,d,message
# just wanted to make things more difficult for you
# who reads CSV files with computers, anyway?
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
Out[28]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
# pandas 能自动识别缺失值
!cat data/ch06/ex5.csv
result = pd.read_csv('data/ch06/ex5.csv')
result
pd.isnull(result)
something,a,b,c,d,message
one,1,2,3,4,NA
two,5,6,,8,world
three,9,10,11,12,foo
Out[29]:
something a b c d message
0 False False False False False True
1 False False False True False False
2 False False False False False False
# 指定缺失标志(如何判断缺失)
result = pd.read_csv('data/ch06/ex5.csv', na_values=['NULL'])
result
Out[30]:
something a b c d message
0 one 1 2 3.0 4 NaN
1 two 5 6 NaN 8 world
2 three 9 10 11.0 12 foo
# 为每列指定不同的判断缺失标志
sentinels = {'message': ['foo', 'NA'], 'something': ['two']}
pd.read_csv('data/ch06/ex5.csv', na_values=sentinels)
Out[31]:
something a b c d message
0 one 1 2 3.0 4 NaN
1 NaN 5 6 NaN 8 world
2 three 9 10 11.0 12 NaN

逐块读取

result = pd.read_csv('data/ch06/ex6.csv')
result.head()
Out[34]:
one two three four key
0 0.467976 -0.038649 -0.295344 -1.824726 L
1 -0.358893 1.404453 0.704965 -0.200638 B
2 -0.501840 0.659254 -0.421691 -0.057688 G
3 0.204886 1.074134 1.388361 -0.982404 R
4 0.354628 -0.133116 0.283763 -0.837063 Q
#读取5行
pd.read_csv('data/ch06/ex6.csv', nrows=5)
Out[35]:
one two three four key
0 0.467976 -0.038649 -0.295344 -1.824726 L
1 -0.358893 1.404453 0.704965 -0.200638 B
2 -0.501840 0.659254 -0.421691 -0.057688 G
3 0.204886 1.074134 1.388361 -0.982404 R
4 0.354628 -0.133116 0.283763 -0.837063 Q
# chunksize: 设置逐块读取的行数
chunker = pd.read_csv('data/ch06/ex6.csv', chunksize=1000)
# 返回一个 reader
chunker
Out[37]:
<pandas.io.parsers.TextFileReader at 0x10f8be2e8>
#  对chunker 进行遍历 ,  逐块计算

chunker = pd.read_csv('data/ch06/ex6.csv', chunksize=1000)
tot = Series([])
for piece in chunker:
    tot = tot.add(piece['key'].value_counts(), fill_value=0)
#tot = tot.sort_values(ascending=False)
tot[:10]
Out[48]:
0    151.0
1    146.0
2    152.0
3    162.0
4    171.0
5    157.0
6    166.0
7    164.0
8    162.0
9    150.0
dtype: float64

输出文本文件

data = pd.read_csv('data/ch06/ex5.csv')
data
Out[49]:
something a b c d message
0 one 1 2 3.0 4 NaN
1 two 5 6 NaN 8 world
2 three 9 10 11.0 12 foo
#  输出csv文件
data.to_csv(sys.stdout) 
,something,a,b,c,d,message
0,one,1,2,3.0,4,
1,two,5,6,,8,world
2,three,9,10,11.0,12,foo
#  指定分隔符
data.to_csv(sys.stdout, sep='|') 
|something|a|b|c|d|message
0|one|1|2|3.0|4|
1|two|5|6||8|world
2|three|9|10|11.0|12|foo
# 指定缺失值的输出
data.to_csv(sys.stdout, na_rep='NULL')
,something,a,b,c,d,message
0,one,1,2,3.0,4,NULL
1,two,5,6,NULL,8,world
2,three,9,10,11.0,12,foo
# 禁止输出标题和索引
data.to_csv(sys.stdout, index=False, header=False)
one,1,2,3.0,4,
two,5,6,,8,world
three,9,10,11.0,12,foo
# 指定标题
data.to_csv(sys.stdout, index=False, columns=['a', 'b', 'c'])
a,b,c
1,2,3.0
5,6,
9,10,11.0
#  输出 Series

dates = pd.date_range('1/1/2000', periods=7)
ts = Series(np.arange(7), index=dates)
ts.to_csv(sys.stdout)
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
# 读取 Series
Series.from_csv('data/ch06/tseries.csv', parse_dates=True)
Out[58]:
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
dtype: int64

手工处理分隔符

对于不规范的文件,经常需要进行预处理。

Python内置的csv模块可以读取任何单字符分隔符文件。 通过定义csv.Dialect参数,可定义适应很多格式(如专门的分隔符、字符串引用约定、行结束符等)。

csv.Dialect 的主要属性包括:

  • delimiter: 分隔符,默认为“,”
  • lineterminator: 行结束符,默认为“\r\n” 。 只作用于写操作,读的时候自动识别。
  • quotechar: 特殊字符的引用符,默认为双引号
  • quoting: 引用约定?
  • skipinitialspace: 是否忽略分隔符后的空白符,默认为 False
  • doublequote: 是否双写字段内的引用符号。默认为 True
  • escapechar: 对分隔符进行转义的字符串?
!cat data/ch06/ex7.csv
"a","b","c"
"1","2","3"
"1","2","3","4"
import csv
f = open('data/ch06/ex7.csv')

reader = csv.reader(f)
for line in reader:
    print(line)
['a', 'b', 'c']
['1', '2', '3']
['1', '2', '3', '4']
lines = list(csv.reader(open('data/ch06/ex7.csv')))
header, values = lines[0], lines[1:]
data_dict = {h: v for h, v in zip(header, zip(*values))}
data_dict
Out[12]:
{'a': ('1', '1'), 'b': ('2', '2'), 'c': ('3', '3')}
class my_dialect(csv.Dialect):
    lineterminator = '\n'
    delimiter = ';'
    quotechar = '"'
    quoting = csv.QUOTE_MINIMAL
# 用 csv 模块输出到文件
with open('mydata.csv', 'w') as f:
    writer = csv.writer(f, dialect=my_dialect)
    writer.writerow(('one', 'two', 'three'))
    writer.writerow(('1', '2', '3'))
    writer.writerow(('4', '5', '6'))
    writer.writerow(('7', '8', '9'))
%cat mydata.csv
one;two;three
1;2;3
4;5;6
7;8;9

JSON 数据

obj = """
{"name": "Wes",
 "places_lived": ["United States", "Spain", "Germany"],
 "pet": null,
 "siblings": [{"name": "Scott", "age": 25, "pet": "Zuko"},
              {"name": "Katie", "age": 33, "pet": "Cisco"}]
}
"""
import json
result = json.loads(obj)
result
Out[19]:
{'name': 'Wes',
 'pet': None,
 'places_lived': ['United States', 'Spain', 'Germany'],
 'siblings': [{'age': 25, 'name': 'Scott', 'pet': 'Zuko'},
  {'age': 33, 'name': 'Katie', 'pet': 'Cisco'}]}
asjson = json.dumps(result)
siblings = DataFrame(result['siblings'], columns=['name', 'age'])
siblings
Out[21]:
name age
0 Scott 25
1 Katie 33

XML 和 HTML: Web 信息收集

NB. The Yahoo! Finance API has changed and this example no longer works

from lxml.html import parse
from urllib2 import urlopen

parsed = parse(urlopen('http://finance.yahoo.com/q/op?s=AAPL+Options'))

doc = parsed.getroot()
links = doc.findall('.//a')
links[15:20]
lnk = links[28]
lnk
lnk.get('href')
lnk.text_content()
urls = [lnk.get('href') for lnk in doc.findall('.//a')]
urls[-10:]
tables = doc.findall('.//table')
calls = tables[9]
puts = tables[13]
rows = calls.findall('.//tr')
def _unpack(row, kind='td'):
    elts = row.findall('.//%s' % kind)
    return [val.text_content() for val in elts]
_unpack(rows[0], kind='th')
_unpack(rows[1], kind='td')
from pandas.io.parsers import TextParser

def parse_options_data(table):
    rows = table.findall('.//tr')
    header = _unpack(rows[0], kind='th')
    data = [_unpack(r) for r in rows[1:]]
    return TextParser(data, names=header).get_chunk()
call_data = parse_options_data(calls)
put_data = parse_options_data(puts)
call_data[:10]

使用 lxml.objectify 解析 XML

path = './data/ch06/mta_perf/Performance_MNR.xml'
from lxml import objectify

parsed = objectify.parse(open(path))
root = parsed.getroot()
data = []

skip_fields = ['PARENT_SEQ', 'INDICATOR_SEQ',
               'DESIRED_CHANGE', 'DECIMAL_PLACES']

for elt in root.INDICATOR:
    el_data = {}
    for child in elt.getchildren():
        if child.tag in skip_fields:
            continue
        el_data[child.tag] = child.pyval
    data.append(el_data)
perf = DataFrame(data)
perf
Out[12]:
AGENCY_NAME CATEGORY DESCRIPTION FREQUENCY INDICATOR_NAME INDICATOR_UNIT MONTHLY_ACTUAL MONTHLY_TARGET PERIOD_MONTH PERIOD_YEAR YTD_ACTUAL YTD_TARGET
0 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 95 1 2008 96.9 95
1 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95 95 2 2008 96 95
2 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 95 3 2008 96.3 95
3 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 98.3 95 4 2008 96.8 95
4 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95.8 95 5 2008 96.6 95
5 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 94.4 95 6 2008 96.2 95
6 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96 95 7 2008 96.2 95
7 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.4 95 8 2008 96.2 95
8 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 93.7 95 9 2008 95.9 95
9 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.4 95 10 2008 96 95
10 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 95 11 2008 96.1 95
11 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95.1 95 12 2008 96 95
12 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 92.6 96.2 1 2009 92.6 96.2
13 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.8 96.2 2 2009 94.6 96.2
14 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 96.2 3 2009 95.4 96.2
15 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 97.1 96.2 4 2009 95.9 96.2
16 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 97.8 96.2 5 2009 96.2 96.2
17 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 97.3 96.2 6 2009 96.4 96.2
18 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.7 96.2 7 2009 96.5 96.2
19 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95.7 96.2 8 2009 96.4 96.2
20 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.1 96.2 9 2009 96.3 96.2
21 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 94.8 96.2 10 2009 96.2 96.2
22 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95.7 96.2 11 2009 96.1 96.2
23 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95 96.2 12 2009 96 96.2
24 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 98 96.3 1 2010 98 96.3
25 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 93 96.3 2 2010 95.6 96.3
26 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 96.3 3 2010 96.1 96.3
27 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 98.1 96.3 4 2010 96.6 96.3
28 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 97.6 96.3 5 2010 96.8 96.3
29 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 97.4 96.3 6 2010 96.9 96.3
... ... ... ... ... ... ... ... ... ... ... ... ...
618 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 94 7 2009 95.14
619 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 8 2009 95.38
620 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 98.3 9 2009 95.7
621 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 98.7 10 2009 96
622 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 98.1 11 2009 96.21
623 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 12 2009 96.5
624 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97.95 97 1 2010 97.95 97
625 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 2 2010 98.92 97
626 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 3 2010 99.29 97
627 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 4 2010 99.47 97
628 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 5 2010 99.58 97
629 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 91.21 97 6 2010 98.19 97
630 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 7 2010 98.46 97
631 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 8 2010 98.69 97
632 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 95.2 97 9 2010 98.3 97
633 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 90.91 97 10 2010 97.55 97
634 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 96.67 97 11 2010 97.47 97
635 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 90.03 97 12 2010 96.84 97
636 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 1 2011 100 97
637 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 100 97 2 2011 100 97
638 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97.07 97 3 2011 98.86 97
639 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 98.18 97 4 2011 98.76 97
640 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 79.18 97 5 2011 90.91 97
641 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 6 2011 97
642 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 7 2011 97
643 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 8 2011 97
644 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 9 2011 97
645 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 10 2011 97
646 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 11 2011 97
647 Metro-North Railroad Service Indicators Percent of the time that escalators are operat... M Escalator Availability % 97 12 2011 97

648 rows × 12 columns

root
Out[13]:
<Element PERFORMANCE at 0x1157d9408>
root.get('href')
root.text

二进制文件

pickle 格式

frame = pd.read_csv('data/ch06/ex1.csv')
frame
Out[17]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
# 实现数据的二进制格式最简单的方法之一是使用Python内置的pickle序列化
# pickle,作者建议用作短期存储,因为会遇到解析版本问题

# 写入二进制文件
frame.to_pickle('frame_pickle')
pd.read_pickle('frame_pickle')
Out[22]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo

使用 HDF5 格式

很多工具都能实现高效读写磁盘上以二进制格式存储的科学数据。HDF5就是一个流行工业级库,是一个C库,有Java、Python、MATLAB等多种接口。

HDF 是指层次型数据格式(hierarchical data format),非常适合存储时间序列数据。

HDF5 支持多种格式的即时压缩,能高效存储重复数据。

HDF5 读写速度极快。

python 中提供了两个 HDF5格式的工具:PyTablesh5py。h5py 更高级,而 PyTables 提供了更多的细节。 pandas 使用了 PyTables 作为 HDF5 的底层支持。

store = pd.HDFStore('mydata.h5')
store['obj1'] = frame
store['obj1_col'] = frame['a']
store
Out[23]:
<class 'pandas.io.pytables.HDFStore'>
File path: mydata.h5
/obj1                frame        (shape->[3,5])
/obj1_col            series       (shape->[3])  
store['obj1']
Out[24]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
store.close()
os.remove('mydata.h5')

读取Excel数据

底层使用 xlrdopenpyxl

xls_file = pd.ExcelFile('data/ch06/ex1.xlsx')
xls_file
Out[36]:
<pandas.io.excel.ExcelFile at 0x116d91b38>
xls_file.parse()
Out[37]:
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo

通过 HTML 和 Web APIs 获取数据

import requests
url = 'https://api.github.com/repos/pydata/pandas/milestones/28/labels'
resp = requests.get(url)
resp
Out[30]:
<Response [200]>
# data[:5]
issue_labels = DataFrame(data)
issue_labels.head()
Out[32]:
AGENCY_NAME CATEGORY DESCRIPTION FREQUENCY INDICATOR_NAME INDICATOR_UNIT MONTHLY_ACTUAL MONTHLY_TARGET PERIOD_MONTH PERIOD_YEAR YTD_ACTUAL YTD_TARGET
0 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 95 1 2008 96.9 95
1 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95 95 2 2008 96 95
2 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 96.9 95 3 2008 96.3 95
3 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 98.3 95 4 2008 96.8 95
4 Metro-North Railroad Service Indicators Percent of commuter trains that arrive at thei... M On-Time Performance (West of Hudson) % 95.8 95 5 2008 96.6 95

使用数据库

import sqlite3

query = """
CREATE TABLE test
(a VARCHAR(20), b VARCHAR(20),
 c REAL,        d INTEGER
);"""

con = sqlite3.connect(':memory:')
con.execute(query)
con.commit()
data = [('Atlanta', 'Georgia', 1.25, 6),
        ('Tallahassee', 'Florida', 2.6, 3),
        ('Sacramento', 'California', 1.7, 5)]
stmt = "INSERT INTO test VALUES(?, ?, ?, ?)"

con.executemany(stmt, data)
con.commit()
cursor = con.execute('select * from test')
rows = cursor.fetchall()
rows
Out[40]:
[('Atlanta', 'Georgia', 1.25, 6),
 ('Tallahassee', 'Florida', 2.6, 3),
 ('Sacramento', 'California', 1.7, 5)]
cursor.description
Out[41]:
(('a', None, None, None, None, None, None),
 ('b', None, None, None, None, None, None),
 ('c', None, None, None, None, None, None),
 ('d', None, None, None, None, None, None))
DataFrame(rows, columns=zip(*cursor.description)[0])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-1d88cef6e699> in <module>()
----> 1 DataFrame(rows, columns=zip(*cursor.description)[0])

TypeError: 'zip' object is not subscriptable
import pandas.io.sql as sql
sql.read_sql('select * from test', con)
Out[43]:
a b c d
0 Atlanta Georgia 1.25 6
1 Tallahassee Florida 2.60 3
2 Sacramento California 1.70 5

参考资料