【问题标题】:How to put the output of a function into a dataframe? [duplicate]如何将函数的输出放入数据框中? [复制]
【发布时间】:2020-05-10 11:13:01
【问题描述】:
def sentiment_analyzer_scores(sentence):
    for sentence in df['clean_text']:
        score =analyser.polarity_scores(sentence)

        print({<40{}".format(sentence,str(score)))

print(sentiment_analyzer_scores(df['clean_text'])

这是我想将输出放入数据框的代码我该怎么做?

【问题讨论】:

  • 使用return - 但您需要先将所有值放入列表中,然后返回列表。或将所有字符串连接到一个字符串中。
  • 你想在新列中放入相同的DataFrame吗?也许你应该使用.apply()

标签: python pandas dataframe


【解决方案1】:

一般情况下,您可以通过这种方式创建新列:

import pandas as pd
df = pd.DataFrame({'col':['hello', 'bye']})
df['len'] = df['col'].apply(len)
print(df)

输出:

     col  len
0  hello    5
1    bye    3

在你的情况下,我认为这样的事情应该有效:

df['new_column'] = df['clean_text'].apply(analyser.polarity_scores)

其中polarity_scores是您要应用的函数

或者是这样的:

df['new_column'] = df['clean_text'].apply(lambda x:"{}<40{}".format(x, str(analyser.polarity_scores(x))))

【讨论】:

    【解决方案2】:

    要从函数中获取数据,您必须将所有字符串保留在列表中 - 没有 print() 并使用 return 返回它

    def sentiment_analyzer_scores(data):
        results = []
        for sentence in data:
            score = analyser.polarity_scores(sentence)
            text = "{<40{}".format(sentence, str(score))
            results.append(text)
    
        return results
    
    df['results'] = sentiment_analyzer_scores(df['clean_text'])
    

    或在新的DataFrame

    results = sentiment_analyzer_scores(df['clean_text'])
    new_df = pd.DataFrame(results)
    

    但也许你应该使用.apply() instread of for-loop

    或多或少

    def sentiment_analyzer_scores(sentence):
        score = analyser.polarity_scores(sentence)
        returm "{<40{}".format(sentence, str(score))
    
    df['results'] = df['clean_text'].apply(sentiment_analyzer_scores)
    

    或在新的DataFrame

    results = df['clean_text'].apply(sentiment_analyzer_scores)
    new_df = pd.DataFrame(results)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 2014-02-14
      • 1970-01-01
      • 2020-01-21
      相关资源
      最近更新 更多