如何将函数的输出放入数据框?

时间:2020-01-24 06:02:18

标签: python pandas dataframe

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'])

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

2 个答案:

答案 0 :(得分: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))))

答案 1 :(得分:0)

要从函数中获取数据,您必须将所有字符串保留在列表中-不使用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()循环的for插入

或多或少

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)