【问题标题】:Why do I have None ('NoneType' object is not iterable) when I expected a list?当我期望一个列表时,为什么我没有('NoneType' 对象不可迭代)?
【发布时间】:2021-12-30 10:03:09
【问题描述】:

我正在使用 pandas.read_sql 检索表名列表,然后尝试使用“for”循环从检索到的列表中删除表。但是,我收到“NoneType”对象不可迭代错误(尽管列表不为空)。

print(type(out_tables_list))
<class 'list'>
print(out_tables_list is None)
False
tables = pd.read_sql("""
SHOW TABLES IN P_SMO_INP_T
""", con=connection)

tableName = tables.tableName
out_tables = tableName[tableName.str.contains('_sg_')]
out_tables_list = out_tables.to_list()

for name in out_tables_list:
    pd.read_sql("DROP TABLE P_SMO_INP_T.{}".format(name), con=connection)

你能帮我弄清楚我的错误是什么吗?提前谢谢!

LE:请参阅下面我收到的完整输出:

TypeError                                 Traceback (most recent call last)
<ipython-input-46-1e7a629dac7d> in <module>
      1 for name in out_tables_list:
----> 2     pd.read_sql("DROP TABLE P_SMO_INP_T.{}".format(name), con=connection)

c:\users\sgulunga\appdata\local\programs\python\python38-32\lib\site-packages\pandas\io\sql.py in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
    481 
    482     if isinstance(pandas_sql, SQLiteDatabase):
--> 483         return pandas_sql.read_query(
    484             sql,
    485             index_col=index_col,

c:\users\sgulunga\appdata\local\programs\python\python38-32\lib\site-packages\pandas\io\sql.py in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize)
   1726         args = _convert_params(sql, params)
   1727         cursor = self.execute(*args)
-> 1728         columns = [col_desc[0] for col_desc in cursor.description]
   1729 
   1730         if chunksize is not None:

TypeError: 'NoneType' object is not iterable

【问题讨论】:

  • 哪一行引发了错误?
  • 你问错问题了。问题应该是“为什么我有 None 当我期望一些可迭代的东西时,比如一个列表?”作为新用户,请拨打tour阅读How to Ask
  • @azro 最后一行引发错误pd.read_sql("DROP TABLE P_SMO_INP_T.{}".format(name), con=connection)
  • 如果我没记错的话,read_sql 将执行一条 SQL 命令并从返回的行中构建一个数据框DROP TABLE 返回的行是什么?

标签: python pandas nonetype read-sql


【解决方案1】:

DROP 查询不返回任何内容,因此 None,因此 pandas 无法对其进行迭代以构建数据框。

How do I drop a table in SQLAlchemy when I don't have a table object?


请注意,调试时要小心引发错误的行,您说“虽然列表不为空”但引发错误的行不使用列表

【讨论】:

  • 感谢您的澄清!我知道如何解决它。我这边的菜鸟失误。
  • @SergiuSRG:请接受答案。它给了 azro 一些代表,并告诉其他人你的问题得到了回答。
猜你喜欢
  • 2018-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 2011-03-26
  • 2021-11-11
  • 2011-08-09
  • 2016-02-08
相关资源
最近更新 更多