繁体   English   中英

使用 if else 语句对 dataframe 进行情绪分析

[英]sentiment analysis of a dataframe using if else statements

我使用这个 function 获得了形容词:

def getAdjectives(text):

    blob=TextBlob(text)
    return [ word for (word,tag) in blob.tags if tag == "JJ"]

dataset['adjectives'] = dataset['text'].apply(getAdjectives)`

我使用以下代码从 json 文件中获取了 dataframe:

with open('reviews.json') as project_file:    
    data = json.load(project_file)
dataset=pd.json_normalize(data) 
print(dataset.head())

我已经使用以下代码对 dataframe 进行了情绪分析:

dataset[['polarity', 'subjectivity']] = dataset['text'].apply(lambda text: pd.Series(TextBlob(text).sentiment))
print(dataset[['adjectives', 'polarity']])

这是 output:


                                          adjectives  polarity
0                                                 []  0.333333
1  [right, mad, full, full, iPad, iPad, bad, diff...  0.209881
2                             [stop, great, awesome]  0.633333
3                                          [awesome]  0.437143
4                        [max, high, high, Gorgeous]  0.398333
5                                     [decent, easy]  0.466667
6  [it’s, bright, wonderful, amazing, full, few...  0.265146
7                                       [same, same]  0.000000
8         [old, little, Easy, daily, that’s, late]  0.161979
9                       [few, huge, storage.If, few]  0.084762

我试图过滤形容词,以确定这段代码中具有正极性、中性极性和负极性的形容词:

if dataset['polarity']> 0:
    print(dataset[['adjectives', 'polarity']], "Positive")
        
elif dataset['polarity'] == 0:
    print(dataset[['adjectives', 'polarity']], "Neutral")   
else: 
        print(dataset[['adjectives', 'polarity']], "Negative")

我得到了错误:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

请帮忙。

尝试使用np.select来确定基于极性的情绪:

df['sentiment'] = np.select(
    [
        dataset['polarity'] > 0,
        dataset['polarity'] == 0
    ],
    [
        "Positive",
        "Neutral"
    ],
    default="Negative"
)

单线:

df['sentiment'] = np.select([dataset['polarity'] > 0, dataset['polarity'] == 0], ["Positive", "Neutral"], "Negative")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM