我想指定执行 pandas.read_sql 时返回的数据类型。我特别感兴趣的是节省内存并将浮点值返回为 np.float32 而不是 np.float64。我知道我可以随后使用 astype(np.float32) 进行转换,但这并不能解决初始查询中的大内存需求问题。在我的实际代码中,我将提取 8400 万行,而不是此处显示的 5 行。 pandas.read_csv 允许将 dtypes 指定为字典,但我认为无法使用 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
你可以使用熊猫读sql查询 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql_query.html它允许您指定返回的数据类型(仅从 pandas 1.3 开始支持)。
pd.read_sql_query('select ARP, ACP from train where seq < 5', connection,
dtype={'ARP': np.float32, 'ACP': np.float32})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)