在pandas中为read_sql指定dtypes

问题描述 投票:8回答:2

我想指定在执行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
python-2.7 pandas mysql-python
2个回答
1
投票

那么cast()和convert()呢?

'SELECT cast(ARP as float32()), cast (ACP as float32()) from train where seq < 5'

或类似的东西。

http://www.smallsql.de/doc/sql-functions/system/convert.html


0
投票

看看this github问题,看起来他们倾向于添加选项。

© www.soinside.com 2019 - 2024. All rights reserved.