【发布时间】:2016-12-24 08:07:41
【问题描述】:
我想指定执行 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 在运行时使用的内存似乎比最终 DataFrame 存储所需的内存要多得多(大约 2 倍)。
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
【问题讨论】:
-
这也可以避免在你有 NaN 时将整数列转换为浮点数。
标签: python-2.7 pandas mysql-python