使用numpy更改dataframe列的dtype

yhuiod9q  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(205)

我正在使用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')
8oomwypt

8oomwypt1#

对于object列,将模式从TEXT转换为VARCHARconnectorx将返回字符串而不是字节。
对于numeric列,不幸的是,你不能做任何事情,但从Int64向下转换到int64应该没有性能问题。connectorx显式使用pd.Int64Int64int64之间的区别本质上是允许空值而不转换到float64

相关问题