【问题标题】:Pandas - TypeError: 'NoneType' object is not iterablePandas - TypeError:“NoneType”对象不可迭代
【发布时间】:2020-07-14 23:24:24
【问题描述】:

对于当前项目,我想遍历 Pandas DataFrame 中定义为 common_words 的单词对列表。

当调用for word in common_words: 行时,我收到错误TypeError: 'NoneType' object is not iterable。我已经检查了可能的方法来解决这个问题,但还没有找到任何解决方案。

有什么聪明的调整可以让它运行吗?

对应的代码部分如下所示:

# Open the file to write to
with open('sp500-1.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    # Write headers
    writer.writerow(["Section", "TFI"])

    # Loop over the JSON objects
    for i in ['txt_pro','txt_con','txt_adviceMgmt','txt_main']:

        # Loop over the common words inside the JSON object
        common_words = get_top_n_bigram_Group2(df[i], 500)
        for word in common_words:

            # Print and write row.
            print(df2)
            writer.writerow([df2])

get_top_n_bigram_Group2的定义如下:

def get_top_n_bigram_Group2(corpus, n=None):
    # settings that you use for count vectorizer will go here
    tfidf_vectorizer=TfidfVectorizer(ngram_range=(2, 2), stop_words='english', use_idf=True).fit(corpus)

    # just send in all your docs here
    tfidf_vectorizer_vectors=tfidf_vectorizer.fit_transform(corpus)

    # get the first vector out (for the first document)
    first_vector_tfidfvectorizer=tfidf_vectorizer_vectors[0]

    # place tf-idf values in a pandas data frame
    df1 = pd.DataFrame(first_vector_tfidfvectorizer.T.todense(), index=tfidf_vectorizer.get_feature_names(), columns=["tfidf"])
    df2 = df1.sort_values(by=["tfidf"],ascending=False)

    print(df2)

【问题讨论】:

  • 根据错误,看起来common_wordsNone。你检查过你的函数的输出来验证返回吗?
  • 感谢您的意见,我明白您的意思。终端中的打印输出正在工作。有没有办法将 common_words 分配给正确的数据? (您很可能需要更多代码)
  • 我已附加get_top_n_bigram_Group2 的代码。如果在这种情况下可以找到为什么common_wordsNone 的解决方案,那就太好了。非常感谢。
  • 你没有在你的函数中return。如果没有 return 语句,函数会隐式返回 None
  • 这能回答你的问题吗? return, return None, and no return at all?

标签: python pandas dataframe


【解决方案1】:

这个函数不返回任何东西,

# Loop over the common words inside the JSON object
common_words = get_top_n_bigram_Group2(df[i], 500)

如果您熟悉 C、C#、C++ 或 Java 等其他语言,就像在函数之前使用 void 关键字一样 get_top_n_bigram_Group2() 在其他语言中返回 void 或 null 但 python 使用 None 和错误

TypeError: 'NoneType' 对象不可迭代

告诉你它不是像字符串、列表、字典或元组那样的迭代器,所以你不能对它们使用索引,或者在这种情况下用于循环。

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 2015-11-04
    • 2012-08-25
    • 1970-01-01
    • 2020-01-11
    • 2017-08-29
    相关资源
    最近更新 更多