成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

在pandas.DataFrame.to_sql時指定數(shù)據(jù)庫表的列類型

DandJ / 4276人閱讀

摘要:分析通過查閱的文檔,可以通過指定參數(shù)值來改變數(shù)據(jù)庫中創(chuàng)建表的列類型。根據(jù)描述,可以在執(zhí)行方法時,將映射好列名和指定類型的賦值給參數(shù)即可上,其中對于表的列類型可以使用包中封裝好的類型。

問題

在數(shù)據(jù)分析并存儲到數(shù)據(jù)庫時,Python的Pandas包提供了to_sql 方法使存儲的過程更為便捷,但如果在使用to_sql方法前不在數(shù)據(jù)庫建好相對應(yīng)的表,to_sql則會默認(rèn)為你創(chuàng)建一個新表,這時新表的列類型可能并不是你期望的。例如我們通過下段代碼往數(shù)據(jù)庫中插入一部分?jǐn)?shù)據(jù):

import pandas as pd
from datetime import datetime

df = pd.DataFrame([["a", 1, 1, 2.0, datetime.now(), True]], 
                  columns=["str", "int", "float", "datetime", "boolean"])
print(df.dtypes)

通過_dtypes_可知數(shù)據(jù)類型為object, int64, float64, datetime64[ns], bool
如果把數(shù)據(jù)通過to_sql方法插入到數(shù)據(jù)庫中:

from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://{}:{}@{}/{}".format("username", "password", "host:port", "database"))
con = engine.connect()

df.to_sql(name="test", con=con, if_exists="append", index=False)

用MySQL的_desc_可以發(fā)現(xiàn)數(shù)據(jù)庫自動創(chuàng)建了表并默認(rèn)指定了列的格式:

# 在MySQL中查看表的列類型
desc test;
Filed Type Null Key Default Extra
str text YES NULL
int bigint(20) YES NULL
float double YES NULL
datetime datetime YES NULL
boolean tinyint(1) YES NULL

其中str類型的數(shù)據(jù)在數(shù)據(jù)庫表中被映射成text,int類型被映射成bigint(20), float類型被映射成double類型。數(shù)據(jù)庫中的列類型可能并非是我們所期望的格式,但我們又不想在數(shù)據(jù)插入前手動的創(chuàng)建數(shù)據(jù)庫的表,而更希望根據(jù)DataFrame中數(shù)據(jù)的格式動態(tài)地改變數(shù)據(jù)庫中表格式。

分析

通過查閱pandas.DataFrame.to_sql的api文檔1,可以通過指定dtype 參數(shù)值來改變數(shù)據(jù)庫中創(chuàng)建表的列類型。

dtype : dict of column name to SQL type, default None 
Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection.

根據(jù)描述,可以在執(zhí)行to_sql方法時,將映射好列名和指定類型的dict賦值給dtype參數(shù)即可上,其中對于MySQL表的列類型可以使用SQLAlchemy包中封裝好的類型。

# 執(zhí)行前先在MySQL中刪除表
drop table test;
from sqlalchemy.types import NVARCHAR, Float, Integer
dtypedict = {
  "str": NVARCHAR(length=255),
  "int": Integer(),
  "float" Float()
}
df.to_sql(name="test", con=con, if_exists="append", index=False, dtype=dtypedict)

更新代碼后,再查看數(shù)據(jù)庫,可以看到數(shù)據(jù)庫在建表時會根據(jù)dtypedict中的列名來指定相應(yīng)的類型。

desc test;
Filed Type Null Key Default Extra
str varchar(255) YES NULL
int int(11) YES NULL
float float YES NULL
datetime datetime YES NULL
boolean tinyint(1) YES NULL
答案

通過分析,我們已經(jīng)知道在執(zhí)行to_sql的方法時,可以通過創(chuàng)建一個類似“{"column_name":sqlalchemy_type}”的映射結(jié)構(gòu)來控制數(shù)據(jù)庫中表的列類型。但在實(shí)際使用時,我們更希望能通過pandas.DataFrame中的column的數(shù)據(jù)類型來映射數(shù)據(jù)庫中的列類型,而不是每此都要列出pandas.DataFrame的column名字。
寫一個簡單的def將pandas.DataFrame中列名和預(yù)指定的類型映射起來即可:

def mapping_df_types(df):
    dtypedict = {}
    for i, j in zip(df.columns, df.dtypes):
        if "object" in str(j):
            dtypedict.update({i: NVARCHAR(length=255)})
        if "float" in str(j):
            dtypedict.update({i: Float(precision=2, asdecimal=True)})
        if "int" in str(j):
            dtypedict.update({i: Integer()})
    return dtypedict

只要在執(zhí)行to_sql前使用此方法獲得一個映射dict再賦值給to_sql的dtype參數(shù)即可,執(zhí)行的結(jié)果與上一節(jié)相同,不再累述。

df = pd.DataFrame([["a", 1, 1, 2.0, datetime.now(), True]], 
                  columns=["str", "int", "float", "datetime", "boolean"])
dtypedict = mapping_df_types(df)
df.to_sql(name="test", con=con, if_exists="append", index=False, dtype=dtypedict)
參考
  • pandas官方文檔 ?

  • 文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

    轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/41296.html

    相關(guān)文章

    • pandas使用

      摘要:寫這篇文章主要是想按照一定的邏輯順總結(jié)一下自己做項目以來序用到過的的知識點(diǎn)雖然官方文檔上各個方面都寫的很清楚但是還是想自己再寫一份一個是想作為個人梳理另外也可以把最經(jīng)常使用的部分拎出來更清晰一些不定時更新數(shù)據(jù)的讀數(shù)據(jù)其中是需要的語句是創(chuàng)建的 寫這篇文章,主要是想按照一定的邏輯順總結(jié)一下自己做項目以來,序用到過的pandas的知識點(diǎn).雖然pandas官方文檔上各個方面都寫的很清楚,但是還...

      int64 評論0 收藏0

    發(fā)表評論

    0條評論

    最新活動
    閱讀需要支付1元查看
    <