Home > Software engineering >  DataFrame update sqlite3 table
DataFrame update sqlite3 table

Time:07-26

have small sqlite3 table that i need to update from dataframe, this

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()

CodePudding user response:

Your code doesn't work because you use f-string in wrong way.

If you want to create query like

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

then you have to add some { } and ' ' 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

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
  • Related