【问题标题】:How to do logical comparison to dataframe column value using cursor excute in pandas如何在熊猫中使用游标执行对数据框列值进行逻辑比较
【发布时间】:2020-05-13 11:12:53
【问题描述】:

我有一个如下所示的数据框 (df)

df

MAX_TIMESTAMP   
2020-01-24 03:07:40

我想从数据框列中传递一个值,并在下面的查询中应用大于比较。

我的查询

cursor.execute("""SELECT * FROM ofs.ord_add oa
        WHERE oa.is_active = 'Y' AND  CREATE_TIMESTAMP > '2020-01-20 08:23:12'""")

data=cursor.fetchall()
columns = [column[0] for column in cursor.description]
status = pd.DataFrame(data,columns=columns)

如何将硬编码值替换为来自数据帧的日期时间参数值?

【问题讨论】:

  • psycopg.org/docs/usage.html 用 %s 或 %(sth)s 替换硬编码值,并用元组或字典引用该值。 create_timestamp > %(sth)s;""" {sth:sth}) 链接应该解释更多
  • @sammywemmy,你能把这个写成答案吗,因为这对未来的读者会有帮助

标签: sql python-3.x pandas dataframe cursor


【解决方案1】:

我引用了这个链接:psycopg2 - usage

用 %s 或 %(sth)s 替换硬编码的值,并用元组或字典引用该值。

cursor.execute(
               """SELECT * FROM ofs.ord_add oa
                  WHERE oa.is_active = 'Y' AND  CREATE_TIMESTAMP > %(sth)s;
               """
               {sth:sth}
                )

链接应该解释更多

【讨论】:

    【解决方案2】:
    sql_query = "SELECT * FROM ofs.ord_add oa WHERE oa.is_active = 'Y' AND  CREATE_TIMESTAMP > %s"
    # Index is the df index of the value 
    index = 0
    
    cursor.execute(sql_query , (df["MAX_TIMESTAMP"].values[index]))
    

    【讨论】:

    • 嘿,它失败了 errorDatabaseError: ORA-01036: illegal variable name/number
    • 嗨,原因可能是在你的 df 中你有 numpy datetime64 类型,但在 db 中日期是字符串。尝试将您的日期值转换为字符串(参考:stackoverflow.com/questions/28694025/…),并且可能确保在元组中发送实际的日期值。更新我。
    • 仍然无法正常工作。在 Db 中,它的 NOT NULL DATE 日期字段和数据框列我使用 `pd.datetime' 将其转换为日期时间格式
    • 很遗憾听到这个消息,我怀疑这里存在日期时间类型不匹配问题,请查看此博客 indradhanush.github.io/blog/… 我希望这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2015-05-11
    相关资源
    最近更新 更多