【问题标题】:How to iterate the list and get the sentiments through pandas dataframe column?如何迭代列表并通过 pandas 数据框列获取情绪?
【发布时间】:2021-04-05 09:20:55
【问题描述】:
How to iterate the list and get the sentiments through pandas dataframe column?

我有一个只有一列的数据框,并且该列中只有 cmets。

data.head()

输出:

    Review
0   If you've ever been to Disneyland anywhere you...
1   Its been a while since d last time we visit HK...
2   Thanks God it wasn t too hot or too humid wh...
3   HK Disneyland is a great compact park. Unfortu...
4   the location is not in the city, took around 1...

我正在使用拥抱脸情绪分类器,例如返回评论的情绪

classifier("My name is mark")

输出是:

[{'label': 'POSITIVE', 'score': 0.9953688383102417}]

只获取标签:

basic_sentiment = [i['label'] for i in value if 'label' in i]
basic_sentiment

输出是:

['POSITIVE']

如何在分类器的dataframe中运行所有给定的cmets并返回输出?

sent = []

for i in text[:]:
  sentiment = classifier(i)
  sent.append(sentiment)

我试过上面的代码,但是它返回错误

【问题讨论】:

    标签: python pandas list dataframe sentiment-analysis


    【解决方案1】:

    我了解您的问题是遍历 pandas 数据框,而不是仅从分类器返回 label

    如果你想返回一个带有分类器()结果的列表,你需要:

    sent = []
    
    for i in range(len(data)):
        sentiment = classifier(data.iloc[i,0])
        sent.append(sentiment)
    

    range(len(data)) 遍历数据帧的所有行。 data.iloc[i,0] 从第 i 行和第 0 列获取值(您只有一列,python 是零索引的)。

    您还可以将分类器的结果保存在另一列中,这样您就有一个包含两列的数据框,一列包含纯文本,另一列包含情绪:

    # initialize new column
    data['Sentiment'] = ''
    
    for i in range(len(data)):
        data.iloc[i,1] = classifier(data.iloc[i,0])
    

    data.iloc[i,1] 定位第 i 行和索引为 1 的列,这是您的第二列(零索引)Sentiment

    如果您只想保存label,则需要将该步骤插入代码中,但是您并不清楚您要保存什么。

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      相关资源
      最近更新 更多