我做了一个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
我不明白我需要在这里更改
答案
最后考虑了下面的评论,并修改了我的生成temp_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)
有2件事使这项工作成功了:
str(ID) & temp_id = ", ".join(temp_id)
答案 0 :(得分:1)
您需要一个字符串,以便内嵌数组
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)
答案 1 :(得分:1)
您需要将变量存储为逗号分隔的字符串而不是数组。
因此,将temp_id声明为字符串。
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)