Search code examples
pythonsentiment-analysishuggingface-transformers

How can I show Label output only from Transformers Pipeline - Sentiment Analysis


Picture of Output

From the picture, I've given the model a few sentences to analyse. The result from the analysis, I've added a new column to the dataframe called "sentiment".

As you can see, it gives the results in a list format with labels and scores.

What i'm trying to do is only add the Label result. i.e: "POSITIVE", "NEGATIVE", etc.. Is there a way of doing this?

Many thanks in advance.


Solution

  • I have no idea how works your pipe but you have list with dict and pandas has .str to work with string but .str[index] works also with list or dict.

    df['Sentiment'] = df['Sentiment'].str[0].str['label']
    

    Minimal working example

    import pandas as pd
    
    df = pd.DataFrame({
       'Sentiment': [
          [{'label':'Negative', 'score': 0.1}],
          [{'label':'Positive', 'score': 0.9}],
       ]      
    }) 
    
    print('\n--- before ---\n')
    print(df)
    
    df['Sentiment'] = df['Sentiment'].str[0].str['label']
    
    print('\n--- after ---\n')
    print(df)
    

    Result:

    --- before ---
    
                                   Sentiment
    0  [{'label': 'Negative', 'score': 0.1}]
    1  [{'label': 'Positive', 'score': 0.9}]
    
    --- after ---
    
      Sentiment
    0  Negative
    1  Positive