代码之家  ›  专栏  ›  技术社区  ›  chowpay

使用列表变量的pandas查询

  •  0
  • chowpay  · 技术社区  · 6 年前

    我列了一个id的列表,每个值都是int类型

    temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623]
    
    type(tempasn) 
    list
    

    这是有效的:

    Temp = pd.read_sql("select count(*) as count\
                        from "+db+"\
                        where ids in (7922, 7018, 5650, 209, 21928, 2294, 10507, 3623)\
                        order by count desc limit 10", conn)
    

    我想把列表中的变量添加到我的查询中

    这会导致错误

    Temp = pd.read_sql("select count(*) as count\
                        from "+db+"\
                        where ids in "+temp_id+"\
                        order by count desc limit 10", conn)
    
    
    TypeError: Can't convert 'list' object to str implicitly
    

    我不明白我在这里需要改变什么


    回答

    最后接受了下面的建议并修改了生成临时ID的循环:

    temp_id = []
    for id in df['ID']:
        if id and id not in temp_id:
            temp_id.append(str(ID))        
    
            #Convert to list format
    temp_id = ", ".join(temp_id)
    

    两件事让这件事成功了:

    str(ID) & temp_id = ", ".join(temp_id)
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Ankur Patel    6 年前

    您需要将变量存储为逗号分隔的字符串,而不是数组。

    所以声明temp_id为string。

    temp_id = "7922, 7018, 5650, 209, 21928, 2294, 10507, 3623"
    
    Temp = pd.read_sql("select count(*) as count\
                        from "+db+"\
                        where ids in ("+temp_id+")\
                        order by count desc limit 10", conn)
    
        2
  •  1
  •   ScaisEdge    6 年前

    你需要一个字符串,所以你应该内爆你的数组

    temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623]
    
    
    my_string = ",".join(temp_id )
    
    Temp = pd.read_sql("select count(*) as count\
                        from "+db+"\
                        where ids in ("+my_string+")\
                        order by count desc limit 10", conn)