【问题标题】:Try and except statements, PythonTry 和 except 语句,Python
【发布时间】:2017-08-23 11:10:16
【问题描述】:

这似乎是一个简单的问题,但我无法通过谷歌搜索和阅读 Stackoverflow 来弄清楚。

我的问题是如何在变量上使用 try 语句并将其附加到列表中?

在下面的示例中,我尝试使用 pandas 从文件列表中获取索引标签。我想将每个转换为一个变量,将它们全部附加到一个列表中并将它们连接起来。但是我很难理解如何尝试“parsed_file.loc["Staff" : "Total Staff"].copy()",并将其转换为要附加到列表的变量。

我有点理解,在下面的示例中,我试图在全局范围内使用局部范围变量,这会引发 NameError。我可以使用函数并在函数中返回变量,但随后我得到一个“TypeError:无法连接非 NDFrame 对象”。我试图将变量转换为函数中的 DataFrame,但它返回相同的错误。

并非所有文件都有索引标签,因此我使用 except: KeyError 来跳过这些文件,并打印文件位置。

for file_ in allFiles:
        parsed_file = read_workbook(file_)
        parsed_file['filename'] = os.path.basename(file_)
        parsed_file.set_index(0, inplace = True)
        parsed_file.index.str.strip()

        try: Staff_ = parsed_file.loc["Staff" : "Total Staff"].copy()
        except KeyError: 
            print(file_)

        list_.append(Staff_)
frame = pd.concat(list_)

【问题讨论】:

  • 您的实际问题是什么?我建议您稍微清理一下您的问题,并更清楚地说明您需要什么帮助..
  • 这不是有效的loc 语法,除非您使用的是MultiIndex dfs。
  • 斯特凡这样更有意义吗?
  • 我不确定我是否理解这个问题,但您似乎可以通过将list_.append(Staff_) 放入try 块中来解决这个问题?然后在异常情况下,Staff_ 不需要定义。

标签: python pandas exception


【解决方案1】:

try 块中的所有内容都将逐行执行,如果发生异常,它将停止执行并跳转到 except 块。因此,我对您的代码进行了一些更改,如果您执行 Staff_ = parsed_file.loc["Staff" : "Total Staff"].copy() 的行出现异常,它将不会执行 try 块中的其余行。这里的文档描述了 try Python Try Catch

for file_ in allFiles:
        parsed_file = read_workbook(file_)
        parsed_file['filename'] = os.path.basename(file_)
        parsed_file.set_index(0, inplace = True)
        parsed_file.index.str.strip()

        try: 
            Staff_ = parsed_file.loc["Staff" : "Total Staff"].copy()
            # Line below won't be executed in case of an exception
            list_.append(Staff_)
        except KeyError: 
            print(file_)

frame = pd.concat(list_)

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 2011-09-29
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多