【问题标题】:Python Change part of a string based on a condition from a listPython根据列表中的条件更改字符串的一部分
【发布时间】:2021-05-27 12:39:54
【问题描述】:

您好,我正在尝试制作一个 python 脚本,每次运行脚本时都会更新一行。

对于如何最好地解决我必须根据数据帧的值更新每一行(选择语句)的部分,我有点头疼。

我得到了一个字符串'select null r_cnt, null t_cnt, null r_dur, null t_dur from my_table'

我得到了一个列表,其中包含此行的字段[t_cnt, r_dur]

然后,我希望新的字符串输出是第一个字符串,其中我们删除了列表中存在的值前面的空值,但在列表中没有的值前面保留了空值。

'select null r_cnt, t_cnt, r_dur, null t_dur from my_table'

我的整个代码现在看起来像这样,我卡在上面提到的点

str_to_execute = f"select * from {db}.table_desc where grp_id in (400,500,300,1200) and id not in(127,140,125)"
    cursor.execute(str_to_execute)
    df = as_pandas(cursor)

    for index, row in df.iterrows():
        # print(row['name'])
        str_to_execute = f"SHOW COLUMN STATS {db}.ctrl_{row['id']}"
        cursor.execute(str_to_execute)
        loop = as_pandas(cursor)
        for index, row in loop.iterrows():
            print(row['Column'])
            
            str_to_execute = f"select concat(cast(ctrl_id as string),cast(ctrl_date as string)) primarykey, ctrl_id, ctrl_date,null r_cnt, null t_cnt, null r_dur, null t_dur,null r_amt, null t_amt,null p_cnt, null p_dur,null p_amt, null ro_vol, null t_vol, null r_vol, null p_vol, null ro_amt, null ro_cnt,    from {db}.ctrl_{row['id']}"
            if #This is where im stuck

【问题讨论】:

    标签: python pandas string dataframe impala


    【解决方案1】:

    试试:

    s = 'select null r_cnt, null t_cnt, null r_dur, null t_dur from my_table'
    lst = ['t_cnt', 'r_dur']
    
    checklist = ['null r_cnt', 'null t_cnt', 'null r_dur']
    checkliststr = ','.join(checklist)
    
    for itm in lst:
        if itm in checkliststr:
            print('null ' + itm)
            s=s.replace('null ' + itm, itm)
    print(s)
    

    【讨论】:

    • 这么好的解决方案,我使用你的 for 循环而不是我自己的第二个循环将它实现到我的代码中。完美运行。谢谢
    • 很高兴知道并感谢您接受答案。
    【解决方案2】:

    在这种情况下,您可以从语句的输入中拆分字符串的功能 Selectfrom my table,如果我正确理解您的字符串列表,这或多或少是。

    一种可能的解决方案如下:

    1. 定义或获取您的字符串列表:

    origin_list = ["null r_cnt", "null t_cnt", "null r_dur", "null t_dur"]

    goal_list = ["t_cnt", "r_dur"]

    1. 对于origin_list 的每个元素,您想根据它在goal_list 中的存在来编辑该元素,我会使用地图和lambda:

    edited_list = list(map(lambda x: edit(x, goal_list), origin_list))

    1. 现在我们必须从您的帖子中定义功能和逻辑,我得出以下逻辑或类似的东西:

    1. 现在您有了调整后的字符串,可以将其与您的功能重新合并。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2021-12-11
      • 2018-08-01
      • 1970-01-01
      • 2017-08-06
      • 2016-08-30
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多