SQLITE3接口 to Arrary

——从数据库加载数据到dataframe/numpy中。

调动 SQLITE3数据库

import sqlite3 as sq3
query = 'CREATE TABLE numbs (Date date, No1 real, No2 real)' con = sq3.connect(path + 'numbs.db')
con.execute(query)
con.commit()

commit 命令

COMMIT 命令是用于把事务调用的更改保存到数据库中的事务命令。

COMMIT 命令把自上次 COMMIT 或 ROLLBACK 命令以来的所有事务保存到数据库

返回值处理

返回所有值,就用 fetchall()。

con.execute('SELECT * FROM numbs').fetchmany(10)

pointer = con.execute('SELECT * FROM numbs')
for i in range(3):
print(pointer.fetchone())

Output:
-------------------------------------------------
('2017-11-18 11:18:51.443295', 0.12, 7.3)
('2017-11-18 11:18:51.466328', 0.9791, -0.01914)
('2017-11-18 11:18:51.466580', -0.88736, 0.19104)

保存到NumPy

第一步、通过初始化直接格式变换即可。

query = 'SELECT * FROM numbers WHERE No1 > 0 AND No2 < 0'

res = np.array( con.execute(query).fetchall() ).round(3)

第二步、可视化数据 by resampling,也就是少取一些点。

res = res[::100]  # every 100th result
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(res[:, 0], res[:, 1], 'ro')
plt.grid(True);
plt.xlim(-0.5, 4.5);
plt.ylim(-4.5, 0.5)
# tag: scatter_query
# title: Plot of the query result
# size: 60

SQLITE3接口 to DataFrame

读取整个表

一张表通常内存可以搞定,全部读取也不是避讳的事情。

import sqlite3 as sq3
filename = path + 'numbs'
con = sq3.Connection(filename + '.db') %time data = pd.read_sql('SELECT * FROM numbers', con)
data.head()

表操作

其实已经演变为 ndarray操作。

“与” 条件

%time data[(data['No1'] > 0) & (data['No2'] < 0)].head()

“或” 条件

%%time
res = data[['No1', 'No2']][((data['No1'] > 0.5) | (data['No1'] < -0.5))
& ((data['No2'] < -1) | (data['No2'] > 1))]

PyTable的快速I/O

HDF5数据库/文件标准。

"无压缩" 创建一个大表

表定义

import numpy as np
import tables as tb
import datetime as dt
import matplotlib.pyplot as plt
%matplotlib inline filename = './data/tab.h5'
h5 = tb.open_file(filename, 'w') # 有几行:多搞几行,弄一个大表
rows = 2000000 # 有几列
row_des = {
'Date': tb.StringCol(26, pos=1),
'No1': tb.IntCol(pos=2),
'No2': tb.IntCol(pos=3),
'No3': tb.Float64Col(pos=4),
'No4': tb.Float64Col(pos=5)
}

创建表

filters = tb.Filters(complevel=0)  # no compression

tab = h5.create_table('/', 'ints_floats', row_des,
title='Integers and Floats',
expectedrows=rows, filters=filters)

新增数据

此时,表还在内存中,向这个表内添加数据。

(1) 一个关键的列表形式。

pointer = tab.row

(2) 生成随机数填充。

ran_int = np.random.randint(0, 10000, size=(rows, 2))
ran_flo = np.random.standard_normal((rows, 2)).round(5)

(3) 赋值给内存中的表。

传统策略,使用了繁琐的循环。

%%time
for i in range(rows):
pointer['Date'] = dt.datetime.now()
pointer['No1'] = ran_int[i, 0]
pointer['No2'] = ran_int[i, 1]
pointer['No3'] = ran_flo[i, 0]
pointer['No4'] = ran_flo[i, 1]
pointer.append()
# this appends the data and
# moves the pointer one row forward

tab.flush()   # 相当于SQLITE3中的commit命令

矩阵策略,省掉了循环。

%%time
sarray['Date'] = dt.datetime.now()
sarray['No1'] = ran_int[:, 0]
sarray['No2'] = ran_int[:, 1]
sarray['No3'] = ran_flo[:, 0]
sarray['No4'] = ran_flo[:, 1]

“压缩” 创建一个大表

创建压缩表

因rows中其实已经有了数据,所以创建的同时就同步写入文件。

filename = './data/tab.h5c'
h5c = tb.open_file(filename, 'w')
filters = tb.Filters(complevel=4, complib='blosc') tabc = h5c.create_table('/', 'ints_floats', sarray,
title='Integers and Floats',
expectedrows=rows, filters=filters)

dnarray读取

读取内存数据,返回 numpy.ndarray。

%time arr_com = tabc.read()
h5c.close()

内存外计算

比如,处理一个若干GB的数组。

创建一个外存数组 EArray

filename = './data/array.h5'
h5 = tb.open_file(filename, 'w') n = 100
ear = h5.create_earray(h5.root, 'ear',
atom=tb.Float64Atom(),
shape=(0, n)) %%time
rand = np.random.standard_normal((n, n))
for i in range(750):
ear.append(rand)
ear.flush() ear.size_on_disk  # 查看一下,这个E Array是个大数组

创建一个对应的 EArray

第一步、设置外存 workspace。

out = h5.create_earray(h5.root, 'out', atom=tb.Float64Atom(), shape=(0, n))

第二步、通过外存来计算ear大数组。

expr = tb.Expr('3 * sin(ear) + sqrt(abs(ear))')    # 这里是 import tables as tb 中的 Expr,而不是import numexpr as ne
# the numerical expression as a string object expr.set_output(out, append_mode=True)
# target to store results is disk-based array %time expr.eval()
# evaluation of the numerical expression
# and storage of results in disk-based array

第三步、从外存读入内存,传的自然是“变量“,而非”workspace"。

%time imarray = ear.read()
# read whole array into memory

  

End.

[Pandas] 04 - Efficient I/O的更多相关文章

  1. Pandas | 04 Panel 面板

    面板(Panel)是3D容器的数据.面板数据一词来源于计量经济学,部分源于名称:Pandas - pan(el)-da(ta)-s. 3轴(axis)这个名称旨在给出描述涉及面板数据的操作的一些语义. ...

  2. [AI] 深度数据 - Data

    Data Engineering Data  Pipeline Outline [DE] How to learn Big Data[了解大数据] [DE] Pipeline for Data Eng ...

  3. Ubuntu下安装python相关数据处理

    01. Ubuntu下安装ipython sudo apt-get install ipython 02. Ubuntu下安装pip $ sudo apt-get install python-pip ...

  4. 数据分析04 /基于pandas的DateFrame进行股票分析、双均线策略制定

    数据分析04 /基于pandas的DateFrame进行股票分析.双均线策略制定 目录 数据分析04 /基于pandas的DateFrame进行股票分析.双均线策略制定 需求1:对茅台股票分析 需求2 ...

  5. 04. Pandas 3| 数值计算与统计、合并连接去重分组透视表文件读取

    1.数值计算和统计基础 常用数学.统计方法 数值计算和统计基础 基本参数:axis.skipna df.mean(axis=1,skipna=False)  -->> axis=1是按行来 ...

  6. Ubuntu16.04下安装配置numpy,scipy,matplotlibm,pandas 以及sklearn+深度学习tensorflow配置+Keras2.0.6(非Anaconda环境)

    1.ubuntu镜像源准备(防止下载过慢): 参考博文:http://www.cnblogs.com/top5/archive/2009/10/07/1578815.html 步骤如下: 首先,备份一 ...

  7. ubuntu16.04安装python3,numpy,pandas等量化计算库

    ubunt安装python3 sudo add-apt-repository ppa:fkrull/deadsnakessudo apt-get updatesudo apt-get install ...

  8. Desktop Ubuntu 14.04LTS/16.04科学计算环境配置

    Desktop Ubuntu 14.04LTS/16.04科学计算环境配置 计算机硬件配置 cpu i5 6代 内存容量 8G gpu GTX960 显存容量 2G(建议显存在4G以上,否则一些稍具规 ...

  9. pandas基础-Python3

    未完 for examples: example 1: # Code based on Python 3.x # _*_ coding: utf-8 _*_ # __Author: "LEM ...

随机推荐

  1. CF553C Love Triangles(二分图)

    Tyher推的好题. 题意就是给你一些好边一些坏边,其他边随意,让你求符合好坏坏~,或者只包含好好好的三元环的无向图个数. 坏坏的Tyher的题意是这样的. 再翻译得更加透彻一点就是:给你一些0(好边 ...

  2. 十款强大的IDEA插件-Java开发者的利器

    xl_echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!! 插 ...

  3. 为什么要用Kubernetes?

    1.前言 第一次接触Kubernetes是在2016年,再一次浏览博文的时候,那是我第一次听到Kubernetes这个名词,也是第一次认识了k8s这么一个东西.后来在慢慢了解它的时候,被它天生高可用. ...

  4. 打印机服务配置篇WindowsServer2008

    本次配置Server2008 打印服务器    目的实现Kingdee远程打印服务,直接在金蝶客户端部署打印机服务器 服务器角色: --打印服务器 --LPD服务 --Internet打印 *打印服务 ...

  5. app发布当天,用户无法登录

    原因:当用户登录时候有商城用户的触发器存在,它会让商城用户也更新成登录状态. 由于用户量大,导致数据库锁死. 最后解决案:删掉触发器,在app的接口登录程序里,追加商城用户更新成登录的操作. 他案1: ...

  6. HDU 4417

    题意略. 思路: 仔细思考这个题目会发现,它其实是要你查询两次,第一是要规定l,r的范围,第二是要在范围内查询小于等于H的个数.所以有的人说要用主席树. 现在,如果我们能省去范围内对h的查询呢?也就是 ...

  7. HDU 6134

    题意略. 思路: 我们先不考虑[(i , j) == 1],在此情况下,其实这个值是sum( [ (i , j) == 1,2,3,....,n ] ) 这些情况.我们要求的仅仅是其中的第一部分而已. ...

  8. 域渗透-LSA Protection

    简介: 微软在 2014 年 3 月 12 日添加了 LSA 保护策略,用来防止对进程 lsass.exe 的代码注入,这样一来就无法使用 mimikatz 对 lsass.exe 进行注入,相关操作 ...

  9. net core天马行空系列: 泛型仓储和声明式事物实现最优雅的crud操作

    系列目录 1.net core天马行空系列:原生DI+AOP实现spring boot注解式编程 哈哈哈哈,大家好,我就是那个高产似母猪的三合,长久以来,我一直在思考,如何才能实现高效而简洁的仓储模式 ...

  10. 在React中使用Bootstrap

    这几天想在react中用一下bootstrap,尽管有一个适配react的很好的库叫react-bootstrap,但我还是想直接使用bootstrap 可以在react项目中执行以下命令安装boot ...