我是Python的新手,正在尝试学习一些基本的数据操作(主要关注数据科学)。所以我还在抓熊猫和其他的东西。我想要实现的是创建一个DataFrame并将其存储在MySQL数据库中。这是我的脚本(不起作用):
from sqlalchemy.types import VARCHAR
from sqlalchemy import create_engine
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.random.random((4,4)),
index=['val1','val2','val3','val4'],
columns=['col1','col2','col3','col4'])
engine = create_engine('mysql+pymysql://user:password@localhost/python_samples')
frame.to_sql('rnd_vals', engine, dtype={'index':VARCHAR(5)})当我尝试执行这个命令时,我得到的错误是MySQL不允许在没有长度的情况下创建文本/BLOB索引:
InternalError: (pymysql.err.InternalError) (1170, "BLOB/TEXT column 'index' used in key specification without a key length") [SQL: 'CREATE INDEX ix_rnd_vals_index ON rnd_vals (`index`)']我相信我可以通过在to_sql()函数上指定dtype选项来解决这个问题,但它没有帮助。我找到了一种方法,通过连接两个DataFrames,一个带有值,另一个带有索引:
from sqlalchemy.types import VARCHAR
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
frame = pd.DataFrame(np.random.random(25).reshape(5,5),
columns=['Jan','Feb','Mar','Apr','May'])
idxFrame = pd.DataFrame({'index':['exp1','exp2','exp3','exp4','exp5']})
frame = frame.join(idxFrame)
frame=frame.set_index('index')
engine = create_engine('mysql+pymysql://user:password@localhost/python_samples')
frame.to_sql('indexes',engine,if_exists='replace', index_label='index',
dtype={'index':VARCHAR(5)})这像预期的那样工作,但我真的怀疑这是不是正确的制作方法,有人能帮我吗?我做错了什么?
谢谢你
发布于 2017-07-26 21:42:23
对于有这个问题的人来说,Ilja Everiläon的评论解决了这个问题。索引名称实际上是'None',而不是' index ',所以当我将dtype从
dtype={'index':VARCHAR(5)}至
dtype={'None':VARCHAR(5)}它解决了这个问题,并在MySQL上创建了该表,如下所示:
CREATE TABLE `rnd_vals` (
`index` text,
`col1` double DEFAULT NULL,
`col2` double DEFAULT NULL,
`col3` double DEFAULT NULL,
`col4` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8不出所料。
谢谢大家!
发布于 2018-09-15 09:13:28
我试图找到一种直接的方法,使熊猫能够直接导入索引。最后,reset_index()似乎是最简单的方法:
my_df.reset_index()
my_df.to_sql(name='my_table', con=engine, index=False, if_exists='replace')发布于 2018-12-19 17:27:57
使用:
frame.to_sql('rnd_vals', engine, dtype={'None':VARCHAR(5)})它在给予:
1170,"BLOB/TEXT列'index‘used in key specification without a key length") SQL: 'CREATE INDEX ix
这解决了问题:
frame.to_sql('indexes',engine,if_exists='replace', index_label='index',dtype={frame.index.name:VARCHAR(5)})https://stackoverflow.com/questions/45285184
复制相似问题