Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The ai.analyze_sentiment function labels each input row as positive, negative, mixed, or neutral. You can also provide custom labels. If the function can't determine sentiment, it leaves the output blank.
Note
- This article covers
ai.analyze_sentimentwith pandas. For PySpark, see Use ai.analyze_sentiment with PySpark. - For all AI Functions and prerequisites, see AI Functions overview.
- Change default configuration for AI Functions with pandas.
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)
Output:
Multimodal input
To analyze sentiment in images, PDFs, or text files, set column_type="path" when the input column contains file path strings. For setup, see Use multimodal input with AI Functions.
# This code uses AI. Always review output for mistakes.
animal_urls = [
"<image-url-golden-retriever>", # Replace with URL to an image of a golden retriever
"<image-url-giant-panda>", # Replace with URL to an image of a giant panda
"<image-url-bald-eagle>", # Replace with URL to an image of a bald eagle
]
animal_df = pd.DataFrame({"file_path": animal_urls})
animal_df["sentiment"] = animal_df["file_path"].ai.analyze_sentiment(column_type="path")
display(animal_df)
Related content
- Use ai.analyze_sentiment with PySpark.
- Learn more about AI Functions.
- Use multimodal input with AI Functions.
- Change default configuration for AI Functions with pandas.
- Understand billing for AI Functions.