1
下列要求:可能使用pandas/sqlalchemy將數組插入到sql數據庫中? (Postgres的)
engine = sqlalchemy.create_engine(url)
df = pd.DataFrame({
"eid": [1,2],
"f_i": [123, 1231],
"f_i_arr": [[123], [0]],
"f_53": ["2013/12/1","2013/12/1",],
"f_53a": [["2013/12/1"], ["2013/12/1"],],
})
with engine.connect() as con:
con.execute("""
DROP TABLE IF EXISTS public.test;
CREATE TABLE public.test
(
eid integer NOT NULL,
f_i INTEGER NULL,
f_i_arr INTEGER NULL,
f_53 DATE NULL,
f_53a DATE[] NULL,
PRIMARY KEY(eid)
);;
""")
df.to_sql("test", con, if_exists='append')
如果我嘗試插入僅列 「f_53」(一個date
)成功爲止。
如果我嘗試添加列「f_53a」(一date[]
)它失敗:
^
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "f_53a" is of type date[] but expression is of type text[]
LINE 1: ..._53, f_53a, f_i, f_i_arr) VALUES (1, '2013/12/1', ARRAY['201...
^
HINT: You will need to rewrite or cast the expression.
[SQL: 'INSERT INTO test (eid, f_53, f_53a, f_i, f_i_arr) VALUES (%(eid)s, %(f_53)s, %(f_53a)s, %(f_i)s, %(f_i_arr)s)'] [parameters: ({'f_53': '2013/12/1', 'f_53a': ['2013/12/1', '2013/12/1'], 'f_i_arr': [123], 'eid': 1, 'f_i': 123}, {'f_53': '2013/12/1', 'f_53a': ['2013/12/1', '2013/12/1'], 'f_i_arr': [0], 'eid': 2, 'f_i': 1231})]
錯誤消息的第一行表示表達式「[」2008-03-08「,]' - 的類型爲'text []'。熊貓可能沒有像'f_53'那樣自動轉換它。你有沒有試過用'pd.to_datetime()'手動轉換它? http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html – bouteillebleu
如果我將所有日期類型更改爲整數和字符串值整數,錯誤是相同的。在這種情況下,熊貓有一列dtype = object保存一個int列表。似乎不是特定於日期,而是數組。 – user48956
確認 - 編輯中的模式錯誤。你是正確的pd.to_datetime日期修復此日期和日期[]插入correctlt – user48956