pandas sql 使用 var 包含列表
pandas sql using var containing list
我通过这样做创建了一个位置列表:
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) 但是
您需要将 list_NA 转换为带单引号的逗号分隔字符串。
"','".join(list_NA)
但您还需要在两端用单引号括起来。
df2 = pd.read_sql("select airport from "+db+" where airport in ('"+ "','".join(list_NA) +"')", conn)
我通过这样做创建了一个位置列表:
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) 但是
您需要将 list_NA 转换为带单引号的逗号分隔字符串。
"','".join(list_NA)
但您还需要在两端用单引号括起来。
df2 = pd.read_sql("select airport from "+db+" where airport in ('"+ "','".join(list_NA) +"')", conn)