Edit

Share via


Use ai.analyze_sentiment with pandas

The ai.analyze_sentiment function uses generative AI to detect the emotional state of the input text, with a single line of code. It can detect whether the emotional state of the input is positive, negative, mixed, or neutral. It can also detect the emotional state according to your specified labels. If the function can't determine the sentiment, it leaves the output blank.

Note

Overview

The ai.analyze_sentiment function extends the pandas Series class. To detect the sentiment of each input row, call the function on a pandas DataFrame text column.

The function returns a pandas Series that contains sentiment labels, which can be stored in a new column of the DataFrame.

Syntax

# Default sentiment labels
df["sentiment"] = df["input"].ai.analyze_sentiment()

# Custom sentiment labels
df["sentiment"] = df["input"].ai.analyze_sentiment("label2", "label2", "label3")

Parameters

Name Description
labels
Optional
One or more strings that represent the set of sentiment labels to match to input text values.

Returns

The function returns a pandas Series that contains sentiment labels for each input text row. The default sentiment labels include positive, negative, neutral, or mixed. If custom labels are specified, those labels are used instead. If a sentiment can't be determined, the return value is null.

Example

# This code uses AI. Always review output for mistakes. 

df = pd.DataFrame([
        "The cleaning spray permanently stained my beautiful kitchen counter. Never again!",
        "I used this sunscreen on my vacation to Florida, and I didn't get burned at all. Would recommend.",
        "I'm torn about this speaker system. The sound was high quality, though it didn't connect to my roommate's phone.",
        "The umbrella is OK, I guess."
    ], columns=["reviews"])

df["sentiment"] = df["reviews"].ai.analyze_sentiment()
display(df)

This example code cell provides the following output:

Screenshot of a data frame with 'reviews' and 'sentiment' columns. The 'sentiment' column includes 'negative', 'positive', 'mixed', and 'neutral'.