我想指定在执行pandas.read_sql时返回的dtypes.特别是我有兴趣保存内存并将浮点值返回为np.float32而不是np.float64.我知道我之后可以使用astype(np.float32)进行转换,但这并不能解决初始查询中大内存需求的问题.在我的实际代码中,我将提取8400万行,而不是这里显示的5行.pandas.read_csv允许将dtypes指定为dict,但我认为使用read_sql无法做到这一点.
我正在使用MySQLdb和Python 2.7.
顺便说一下,read_sql在运行时(大约2x)似乎比最终的DataFrame存储需要更多的内存.
In [70]: df=pd.read_sql('select ARP, ACP from train where seq < 5', connection)
In [71]: df
Out[71]:
ARP ACP
0 1.17915 1.42595
1 1.10578 1.21369
2 1.35629 1.12693
3 1.56740 1.61847
4 1.28060 1.05935
In [72]: df.dtypes
Out[72]:
ARP float64
ACP float64
dtype: object
Run Code Online (Sandbox Code Playgroud) 按照这里的其他帖子,我有一个函数,根据其名称打印出有关变量的信息.我想把它移到一个模块中.
#python 2.7
import numpy as np
def oshape(name):
#output the name, type and shape/length of the input variable(s)
#for array or list
x=globals()[name]
if type(x) is np.array or type(x) is np.ndarray:
print('{:20} {:25} {}'.format(name, repr(type(x)), x.shape))
elif type(x) is list:
print('{:20} {:25} {}'.format(name, repr(type(x)), len(x)))
else:
print('{:20} {:25} X'.format(name, type(t)))
a=np.array([1,2,3])
b=[4,5,6]
oshape('a')
oshape('b')
Run Code Online (Sandbox Code Playgroud)
输出:
a <type 'numpy.ndarray'> (3,)
b <type 'list'> 3
Run Code Online (Sandbox Code Playgroud)
我想把这个函数oshape()放到一个模块中,以便它可以重用.但是,放置在模块中不允许从主模块访问全局变量.我尝试过'import __main__'之类的东西,甚至存储函数globals()并将其传递给子模块.问题是globals()是一个函数,它专门返回调用它的模块的全局变量,而不是每个模块的不同函数.
import numpy as np
import olib
a=np.array([1,2,3])
b=[4,5,6]
olib.oshape('a')
olib.oshape('b')
Run Code Online (Sandbox Code Playgroud)
给我:
KeyError: 'a'
Run Code Online (Sandbox Code Playgroud)
额外信息:目标是减少冗余打字.稍微修改一下(我把它拿出去使问题更简单),oshape可以报告变量列表,所以我可以使用它: …