简体   繁体   English

DataFrame 更新 sqlite3 表

[英]DataFrame update sqlite3 table

have small sqlite3 table that i need to update from dataframe, this有我需要从 dataframe 更新的小 sqlite3 表,这个

upd = f'update test set {row[2] = row[2] + 1} where bin = {row[1]};

If someone please explain me why, thanks.如果有人请解释我为什么,谢谢。

   import pandas as pd
    import sqlite3
    #sqlite3 table
    """CREATE TABLE IF NOT EXISTS "test" (
    "index" INTEGER,
      "bin" TEXT,
      "1" INTEGER,
      "2" INTEGER,
      "3" INTEGER,
      "type" TEXT
    )"""
    
    #connecting to test
    conn = sqlite3.connect('test.db')
    #create df to insert data into the table
    df = pd.DataFrame({'bin':['a', 'b', 'c', 'd', 'e'],\
                        '1':[0,0,0,0,0],\
                        '2':[0,1,0,0,0],\
                        '3':[0,0,0,0,0],\
                        "type":['x','x','x','x','x']})
    #reseting index
    df = df.reset_index(drop=True)
    #adding records
    #df.to_sql('test', conn)
    #this is data-frame that need to update table
    upd = pd.DataFrame({'bin':['b','c'],'date':[2,3]})
    #after update table need to look like this
    desired_output = pd.DataFrame({'bin':['a', 'b', 'c', 'd', 'e'],'1':[0,0,0,0,0],'2':[0,2,0,0,0],'3':[0,0,1,0,0],"type":['x','x','x','x','x']})
    #create cursor for execution
    cursor = conn.cursor()
    #iterate over rows
    for row in upd.itertuples():
        #need update columns while set it dinamicly
        #UPDATE test SET '1'= '1' + 1 Where bin = 'c' -> This works in DB Browser for Sqlite
        #how to select column dynamically?
        upd = f'update test set {row[2] = row[2] + 1} where bin = {row[1]};'
        cursor.execute(upd)
    conn.close()

Your code doesn't work because you use f-string in wrong way.您的代码不起作用,因为您以错误的方式使用f-string

If you want to create query like如果您想创建类似的查询

UPDATE test SET '1'= '1' + 1 WHERE bin = 'c'

then you have to add some { } and ' ' like那么你必须添加一些{ }' ' like

f"UPDATE test SET '{row[2]}' = '{row[2]}' + 1 WHERE bin = '{row[1]}';

But I don't know why you use SQLite if you can do it directly in DataFrame但是我不知道你为什么使用SQLite如果你可以直接在DataFrame

for index, row in upd.iterrows():
    df.loc[ df['bin'] == row['bin'], row['data']] += 1

Minimal working code:最小的工作代码:

import pandas as pd

df = pd.DataFrame({
    'bin': ['a', 'b', 'c', 'd', 'e'],
    '1': [0, 0, 0, 0, 0],
    '2': [0, 1, 0, 0, 0], 
    '3': [0, 0, 0, 0, 0],
    "type": ['x', 'x', 'x', 'x', 'x']
})

upd = pd.DataFrame({'bin': ['b', 'c'], 'data': ['2', '3']})

print('--- before ---')
print(df)

for index, row in upd.iterrows():
    df.loc[ df['bin'] == row['bin'], row['data']] += 1

print('--- after ---')
print(df)

Result:结果:

--- before ---
  bin  1  2  3 type
0   a  0  0  0    x
1   b  0  1  0    x
2   c  0  0  0    x
3   d  0  0  0    x
4   e  0  0  0    x
--- after ---
  bin  1  2  3 type
0   a  0  0  0    x
1   b  0  2  0    x
2   c  0  0  1    x
3   d  0  0  0    x
4   e  0  0  0    x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM