I read the data from the database, then after processing I want to write it to another table.

db = pymysql.connect(host='localhost', user='root', passwd='', database='mom_db', charset='utf8') test = pd.read_sql("SELECT comm FROM comments ", db) test['pred_lr'] = grid_lr.best_estimator_.predict(test['comm']) test['pred_nb'] = grid_nb.best_estimator_.predict(test['comm']) print(test) 

after that, I simply delete the test['comm'] column that is unnecessary (after analysis) and write the rest of the test to the database in the same table :

  del test['comm'] db_connection = 'mysql+pymysql://root@localhost/mom_db' conn = create_engine(db_connection, encoding='utf-8') test.to_sql(name='comments', con=conn, if_exists='append', index=False) 

print(test) results:

  comm pred_lr pred_nb 0 Как только поймали за руку, сразу забегала меж... 1 -1 1 кто-то врёт -1 -1 2 Снова гэта усё правакатары с Польшы 1 -1 3 Мне кажется надо по уголовной статье таких суд... 1 -1 4 Мне пофиг кто там проголосовал, главное что 90... 1 1 5 Прямое доказательство фальсификации, всем и та... 1 1 6 Цитата : "Инцидент не будет иметь влияния на и... 1 1 7 А что она может еще сказать? -1 -1 8 В одном месте он предъявил договор о найме жил... -1 1 9 Она констатировала, что этот случай говорит о ... -1 1 10 Не важно, что он предъявил, если даже левый че... -1 -1 11 Как то вериться больше учителям и т. П. Чем ер... -1 -1 12 Цитата \t\tИриша_Лалапусечка: "Мне кажется над... 1 -1 13 Вся эта власть основана на подлости и лживости. -1 -1 14 Ермошина достаточно опытный человек, чтобы дат... 1 1 15 Цитата \t\tИриша_Лалапусечка: "Мне кажется над... 1 1 16 вот это больше похоже на правду. члены комисси... 1 -1 17 Да жулики эти "активисты",добропорядочный бела... 1 1 18 Выборы-дурыборы. Благо никто не хочет играть с... -1 -1 19 Ермошиной к ответу!!!Провакаторов она нашла,а ... -1 -1 20 Кстати все идет к тому что с этими назойливыми... -1 1 21 А те жэншчины,которых привезли в микроавтобусе... 1 -1 22 Уже всем понятно, что на Западе никто эти выбо... -1 -1 23 Они даже не стесняются нагло фальсифицировать.... -1 -1 24 ничего, что там надо в журнале расписываться п... 1 -1 25 красивая сказка! -1 1 26 Ну вот и ответ.... В стиле сам дурак. Впрочем ... -1 -1 27 Оппозиция у нас подлая,посмотрите к чему оппоз... 1 1 28 А на видео видно, что он сочиняет слезливую ск... -1 -1 29 Факт остается фактом! Это доказывает что выбор... 1 -1 ... ... ... ... 4670 -1 1 4671 -1 1 4672 -1 1 4673 -1 1 4674 -1 1 4675 -1 1 4676 -1 1 4677 -1 1 4678 -1 1 4679 -1 1 4680 -1 1 4681 -1 1 4682 -1 1 4683 -1 1 4684 -1 1 4685 -1 1 4686 -1 1 4687 -1 1 4688 -1 1 4689 -1 1 4690 -1 1 4691 -1 1 4692 -1 1 4693 -1 1 4694 -1 1 4695 -1 1 4696 -1 1 4697 -1 1 4698 -1 1 4699 -1 1 [4700 rows x 3 columns] 

and the pred_lr and pred_nb columns are also added to the database: enter image description here

Can someone suggest how to fix this?

  • and what SHOW VARIABLES LIKE 'character\_set\_%'; says is SHOW VARIABLES LIKE 'character\_set\_%'; if you run this in heidiSQL? - MaxU

1 answer 1

DataFrame.to_sql() does not allow changing ( UPDATE ) data in SQL tables. You can either completely overwrite the contents of the entire table ( if_exists='replace' ) or add new entries ( if_exists='append' ). In the new records there will be only the data that is present in the DataFrame.

If you need to do UPDATE , you can do the following:

First, save the DataFrame to a temporary (by meaning, not by table type in MySQL) table:

 df.to_sql('tmp', conn, if_exists='replace') 

After that, change the necessary columns in MySQL ( this can be done using SQL Alchemy )

 update comments set pred_lr=tmp.pred_lr, pred_nb=tmp.pred_nb FROM comments INNER JOIN tmp on comments.id = tmp.id; 
  • one
    but you can not somehow add values ​​to the columns of existing records? Or overwrite only selected columns? - lynx
  • bypassed the problem by creating a second table. - lynx