从postgres获取数据并根据多种条件替换列的值

问题描述 投票:0回答:1

我获取了postgres表的列,现在我想根据列'A'替换​​列'B'的值。如果该值大于某个值,则替换为'B'的值...我试图写代码,但我不明白我将如何执行if语句...我也试图用panda做到这一点,但我也无法在其中做出逻辑。任何帮助将不胜感激

import psycopg2
import xml.etree.ElementTree as et
connection=psycopg2.connect(user="user",database="db",password="****",host= "localhost")
cursor=connection.cursor()
cursor.execute("select * from mytable")
col_clean=cursor.fetchall()
for row in  col_clean:
     if "a" == 10 :
        'b'.replace(0.000,(9/100))
    elif "a" ==20:
        'b'.replace(0.000,(22/100))
    elif "a" == 30:
        'b'.replace(0.000,(70/100))
    elif "a" == 40:
        'b'.replace(0.000, (80 / 1000))
     ELSE
        'b.replace(0.000, (100 / 100))
cursor.execute('Insert into mytable("b") VALUES(%s)',%row)
connection.commit()
python-3.x postgresql
1个回答
0
投票
import psycopg2 import xml.etree.ElementTree as et connection=psycopg2.connect(user="user",database="db",password="****",host= "localhost") cursor=connection.cursor() cursor.execute("""UPDATE mytable set b = CASE a WHEN '10' THEN 0.09 WHEN '20' THEN 0.22 WHEN '30' THEN 0.70 WHEN '40' THEN 0.80 ELSE 1 END""") connection.commit()

编辑:固定为“ a”为文本。

© www.soinside.com 2019 - 2024. All rights reserved.