我正在使用connectorx库从sql表中获取数据到dataframe中。使用connectorx导致字节字符串格式,我想将其改回通常的格式。
我正在使用下面的代码转换dtype,它非常慢。有没有更快的方法来转换dataframe列的dtype?你能建议如何使用numpy吗?
我的代码使用iris数据集在线提供:
import pandas as pd
import connectorx as cx
import time
db_url="mysql://{user}:{pw}@localhost:{port}/{db}".format(user="cookie",pw="cookie123",db="mydb",port=3306)
query='Select * from test'
iris=cx.read_sql(db_url,query)
for col, dtype in iris.dtypes.items():
if dtype == object:
iris[col] = iris[col].str.decode('utf-8').fillna(iris[col])
elif dtype == 'Int64':
iris[col] = iris[col].astype('int64')
1条答案
按热度按时间8oomwypt1#
对于
object
列,将模式从TEXT
转换为VARCHAR
。connectorx
将返回字符串而不是字节。对于
numeric
列,不幸的是,你不能做任何事情,但从Int64
向下转换到int64
应该没有性能问题。connectorx
显式使用pd.Int64
。Int64
和int64
之间的区别本质上是允许空值而不转换到float64
。