首页 > 解决方案 > pandas sql使用包含列表的var

问题描述

我通过这样做创建了一个位置列表:

list_NA = []
for x in df['place']:
    if x and x not in list_NA:
        list_NA.append(x)

这给了我一个这样的列表:

print(list_NA)

['DEN', 'BOS', 'DAB', 'MIB', 'SAA', 'LAB', 'NYB', 'AGA', 'QRO', 'DCC', 'PBC', 'MIC', 'MDW', 'SAB', 'LAA', 'NYA', 'PHL', 'DCB', 'CHA', 'CHB', 'SEB', 'AGB', 'SEC', 'DAA', 'MEX']

我想在我的 where 子句中使用这个列表,如下所示:

df2 = pd.read_sql("select airport from "+db+" where airport in "+list_NA+"", conn)

但我不断收到此错误:

TypeError: Can't convert 'list' object to str implicitly

我试图做 str(list_NA) 或 tuple(list_NA) 但

标签: mysqlpandaswhere-clause

解决方案


您需要将 list_NA 转换为带单引号的逗号分隔字符串。

"','".join(list_NA)

但您还需要在两端用单引号括起来。

df2 = pd.read_sql("select airport from "+db+" where airport in ('"+ "','".join(list_NA) +"')", conn)

推荐阅读