【问题标题】:How to make simple error handling in Python? [duplicate]如何在 Python 中进行简单的错误处理? [复制]
【发布时间】:2021-05-11 13:30:55
【问题描述】:

当我的脚本在 excel 文件中找不到特定单元格时,它会引发错误并停止整个脚本。我不希望这样的事情发生!

'Total Employees':  '{}'.format(df.iloc[1]['5A'])

来自控制台的错误消息:

Traceback (most recent call last):
  File "c:\Users\szyma\Desktop\python_shit\index.py", line 25, in <module>
    'Total Employees':  '{}'.format(df.iloc[row_iterator]['5A']),
  File "C:\Python39\lib\site-packages\pandas\core\series.py", line 824, in __getitem__
    return self._get_value(key)
  File "C:\Python39\lib\site-packages\pandas\core\series.py", line 932, in _get_value
    loc = self.index.get_loc(label)
  File "C:\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: '5A'

相反,我想粘贴大括号,例如 'empty'。我怎样才能做到这一点?

【问题讨论】:

  • 使用dict.get(key, DEFAULT_VALUE)或使用try ... except KeyError

标签: python


【解决方案1】:
try:
    print('Total Employees :  {}'.format(df.iloc[1]['5A']))
except KeyError:
    print("Total Employees : empty")

【讨论】:

    【解决方案2】:

    'Total Employees': '{}'.format(df.iloc[1].get('5A', 'empty'))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2015-06-18
      • 2013-05-13
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 2021-12-26
      相关资源
      最近更新 更多