我的数据帧没有用SQLAlchemy正确保存

2024-10-01 07:16:22 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码

import datetime
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import MySQLdb

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['John','Pierre', 'Boris']

df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0)
data = np.array([np.arange(10)]*3).T

df = pd.DataFrame(data, index=index, columns=columns)

print (df)

con = MySQLdb.connect(host="localhost",user="milenko",passwd="*******",db="dbase")

engine = create_engine("mysql+mysqldb://milenko:"+'*******'+"@localhost/dbase")
df.to_sql(con=engine,name = 'stek', if_exists='fail', index=True)

我的df看起来像

       John  Pierre  Boris
2017-06-06     0       0      0
2017-06-07     1       1      1
2017-06-08     2       2      2
2017-06-09     3       3      3
2017-06-10     4       4      4
2017-06-11     5       5      5
2017-06-12     6       6      6
2017-06-13     7       7      7
2017-06-14     8       8      8
2017-06-15     9       9      9

但这让人困惑。我的桌子看起来像这样

show columns from  stek;
+--------+------------+------+-----+---------+-------+
| Field  | Type       | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| index  | datetime   | YES  | MUL | NULL    |       |
| John   | bigint(20) | YES  |     | NULL    |       |
| Pierre | bigint(20) | YES  |     | NULL    |       |
| Boris  | bigint(20) | YES  |     | NULL    |       |
+--------+------------+------+-----+---------+-------+

我做错了吗?在哪里?我真正想要的是保留整个数据帧结构,以便对更大的数据集使用这种方法。 我的问题

 SELECT FROM stek WHERE index = 'John';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM stek WHERE index = 'John'' at line 1

Tags: columnsimportdfdatetimedateindexnpjohn