【问题标题】:TypeError: 'NoneType' object is not subscriptable when creating a pd.Dataframe dictionaryTypeError:“NoneType”对象在创建 pd.Dataframe 字典时不可下标
【发布时间】:2018-05-15 13:29:06
【问题描述】:

我收到的错误是:TypeError: 'NoneType' object is not subscriptable

在这个方法中,我试图沿着两个文件(test&master)进行字符串匹配。 主文件包含拼写正确的产品名称,而测试文件包含这些产品的拼写错误或只是拼写不同的版本。 我正在尝试将它们与 extractBests 函数相匹配,以包含某个分数的截止值。此外,如果我打印输出的早期步骤,例如 fhp_new 变量,它仍然有效。

我认为错误是由以下事实引起的,即某些行没有给出任何在 score_cutoff 限制内的匹配项,因为当我将限制设置为 20 时我没有收到错误。所以理论上那些行应该保持为空,但这会导致我认为的错误。

这行代码导致错误:

for x in range (1, num_match + 1):
            d["Match{0}".format(x)] = [y[0] for y in aggregated_matches["Match" + str(x)]]

这是直到错误行的完整代码

def StringMatch (master, testfile, num_match=3, score_cutoff=95, limit=3):
        master_names = master.iloc[:,3]
        test_names = testfile.iloc[:,0]    
        fhp_new = [process.extractBests(x, master_names, score_cutoff=score_cutoff,limit=limit) for x in test_names]
        lab=" "
        i=1

        while i<=num_match:
            lab = lab + " " + "Match" + str(i)
            i = i+1
        aggregated_matches = pd.DataFrame(fhp_new, columns = lab.split())

        d={}
        for x in range (1, num_match + 1):
            d["Match{0}".format(x)] = [y[0] for y in aggregated_matches["Match" + str(x)]]
        print(d)

【问题讨论】:

  • @user202729 怎么做呢?我还是个新手,调试很烂。感谢您的意见!
  • 我告诉过你检查是否有任何对象为 None。如果您想知道某事是否为无,只需将其打印出来。怎么了? ...
  • 错误告诉你你的yNone,所以它可能不是你想象的那样。在 for 循环中,尝试打印聚合匹配:for y in aggregated_matches["Match" + str(x)]: print(y)。看看为什么是None
  • @BramVanroy 因此,对于很多匹配项来说,返回的结果都是无,因为它们不符合我至少 95 分的标准。但我仍然想显示这个。我想要的结果是让列 Match 1,2,3 并在其中显示与此条件匹配的所有匹配项。如果未找到匹配项,请将此行留空,或者如果不可能跳过它。我猜这个错误是因为 Python 不想这样做,所以这就是我正在寻找的解决方法。

标签: python python-3.x fuzzywuzzy


【解决方案1】:

如果我理解正确,你只是想检查一下y is None

def StringMatch (master, testfile, num_match=3, score_cutoff=95, limit=3):
        master_names = master.iloc[:,3]
        test_names = testfile.iloc[:,0]    
        fhp_new = [process.extractBests(x, master_names, score_cutoff=score_cutoff,limit=limit) for x in test_names]
        lab=" "
        i=1

        while i<=num_match:
            lab = lab + " " + "Match" + str(i)
            i = i+1
        aggregated_matches = pd.DataFrame(fhp_new, columns = lab.split())

        d={}
        for x in range (1, num_match + 1):
            d["Match{0}".format(x)] = [None if y is None else y[0] for y in aggregated_matches["Match" + str(x)]]
        print(d)

【讨论】:

  • 感谢您的建议,这真的很有帮助,我能够解决这个错误,现在它告诉我数组必须都是相同的长度,所以我必须找到一种方法来包含将那些 None 放入数组中而不给我原始错误。
  • @Tim 在这种情况下,您可以在列表理解中进行检查,即[None if y is None else y[0] for ...] 查看我的编辑。
  • 谢谢,同时我使用了不同的解决方案,在数据帧上使用 .fillna() 并将 None 替换为字符串,但我也会测试您的解决方案。谢谢!
  • 测试了您的解决方案,它按预期工作。再次感谢您的支持!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 2021-12-14
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
相关资源
最近更新 更多