【问题标题】:Set correct pandas.DataFrame datatypes from cx_Oracle default data types从 cx_Oracle 默认数据类型设置正确的 pandas.DataFrame 数据类型
【发布时间】:2020-05-30 01:12:12
【问题描述】:

我有一些带有下一个字段数据类型的 oracle 表:

ID|              NOT NULL NUMBER              
VERSION|         NOT NULL NUMBER              
STAT_ACTUAL|     NOT NULL NUMBER              
REGION|          NOT NULL VARCHAR2(5 CHAR)    
PARENTID|                 NUMBER              
CITY|                 VARCHAR2(5 CHAR)    
...

如果我试图像这样将它们从 cx_Oracle 添加到 pandas.DataFrame:

import pandas as pd
from sqlalchemy import *

conn = cx_Oracle.connect('datbs/datbs@host/serv')
cursorr = conn.cursor()
SQL  = "select * from table where region = 1"

df= pd.read_sql_query(SQL, con=conn)

数据类型看起来像:

ID                          int64
VERSION                     int64
STAT_ACTUAL                 int64
REGION                     object
PARENTID                    int64
CITY                       object
...

所以,我所有的 oracle varchar2(在 cx_Oracle 中看起来为 ('REGION', <class 'cx_Oracle.STRING'>))都是 pandas.df 中的对象!

我尝试通过以下方式转换它们:

def OutConverter(value):
    if value is None:
        return ''
    return value

def VarToStr(cursor, name, defaultType, size, precision, scale):
    if defaultType in (cx_Oracle.STRING, cx_Oracle.OBJECT):
        return cursor.var(str, size, cursorr.arraysize, outconverter=OutConverter)

conn.outputtypehandler = VarToStr

但是结果还没有被取走...df.dtypes 再次显示对象类型

如何将 oracle 和 cx_Oracle 数据类型映射到 pandas df?

【问题讨论】:

    标签: python pandas oracle cx-oracle


    【解决方案1】:

    我曾使用手动转换不正确的列,例如:

    newdf = df.astype({"REGION": "Int64", ..., "CITY": "Int32", ...})
    

    输出:

    REGION                      int64
    CITY                        Int32
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 2020-09-06
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多