python – MySQL的pandas可以支持文本索引吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – MySQL的pandas可以支持文本索引吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2427字,纯文字阅读大概需要4分钟。
内容图文
![python – MySQL的pandas可以支持文本索引吗?](/upload/InfoBanner/zyjiaocheng/898/5fbb55516fda4079a12fd672fbd28608.jpg)
如果我尝试在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
)
解决方法:
您可以在调用to_sql()方法时使用dtype参数显式指定SQLAlchemy data type:
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())})
我们在MySQL端检查它:
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)
现在让我们把它读回一个新的DF:
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
您可以通过以下方式找到对象列的最大长度:
In [75]: df.index.get_level_values('Id').str.len().max()
Out[75]: 8
内容总结
以上是互联网集市为您收集整理的python – MySQL的pandas可以支持文本索引吗?全部内容,希望文章能够帮你解决python – MySQL的pandas可以支持文本索引吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。