如果我尝试在MySQL数据库中存储带有文本索引的数据帧,我会收到错误“在没有密钥长度的密钥规范中使用BLOB / TEXT列”,例如:
import pandas as pd
import sqlalchemy as sa
df = pd.DataFrame(
{'Id': ['AJP2008H', 'BFA2010Z'],
'Date': pd.to_datetime(['2010-05-05', '2010-07-05']),
'Value': [74.2, 52.3]})
df.set_index(['Id', 'Date'], inplace=True)
engine = sa.create_engine(db_connection)
conn = engine.connect()
df.to_sql('test_table_index', conn, if_exists='replace')
conn.close()
会产生错误:
InternalError: (pymysql.err.InternalError)
(1170, "BLOB/TEXT column 'Id' used in key specification without a key length")
[SQL: 'CREATE INDEX `ix_test_table_index_Id` ON test_table_index (`Id`)']
如果我没有设置索引,它可以正常工作。有没有办法存储它而不直接下载到SQLAlchemy来创建表?
(这是我目前的SQLAlchemy解决方法:
table = Table(
name, self.metadata,
Column('Id', String(ID_LENGTH), primary_key=True),
Column('Date', DateTime, primary_key=True),
Column('Value', String(VALUE_LENGTH)))
sa.MetaData().create_all(engine) # Creates the table if it doens't exist
)
答案 0 :(得分:8)
您可以在调用SQLAlchemy data type方法时使用let numberInt = [23, 10, 79, 3]
let numberString = numberInt.toString()
参数明确指定to_sql():
dtype
让我们在MySQL端检查它:
In [48]: from sqlalchemy.types import VARCHAR
In [50]: df
Out[50]:
Value
Id Date
AJP2008H 2010-05-05 74.2
BFA2010Z 2010-07-05 52.3
In [51]: df.to_sql('test_table_index', conn, if_exists='replace',
dtype={'Id': VARCHAR(df.index.get_level_values('Id').str.len().max())})
现在让我们把它读回一个新的DF:
mysql> show create table test_table_index\G
*************************** 1. row ***************************
Table: test_table_index
Create Table: CREATE TABLE `test_table_index` (
`Id` varchar(8) DEFAULT NULL,
`Date` datetime DEFAULT NULL,
`Value` double DEFAULT NULL,
KEY `ix_test_table_index_Id` (`Id`),
KEY `ix_test_table_index_Date` (`Date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql> select * from test_table_index;
+----------+---------------------+-------+
| Id | Date | Value |
+----------+---------------------+-------+
| AJP2008H | 2010-05-05 00:00:00 | 74.2 |
| BFA2010Z | 2010-07-05 00:00:00 | 52.3 |
+----------+---------------------+-------+
2 rows in set (0.00 sec)
您可以通过以下方式找到对象列的最大长度:
In [52]: x = pd.read_sql('test_table_index', conn, index_col=['Id','Date'])
In [53]: x
Out[53]:
Value
Id Date
AJP2008H 2010-05-05 74.2
BFA2010Z 2010-07-05 52.3