Skip to content

Instantly share code, notes, and snippets.

@marcosan93
Created September 9, 2021 00:07
Show Gist options
  • Select an option

  • Save marcosan93/6ead14235afb05ec85c6dcfdce010098 to your computer and use it in GitHub Desktop.

Select an option

Save marcosan93/6ead14235afb05ec85c6dcfdce010098 to your computer and use it in GitHub Desktop.
def getSentiment(df, measurement="compound"):
"""
Given a DF of tweets, analyzes the tweets and returns a new DF
of sentiment scores based on the given measurement.
Accepted sentiment measurements: ["pos", "neg", "neu", "compound"]
"""
# Sentiment Analyzer
sia = SentimentIntensityAnalyzer()
# Getting the sentiment score
df['sentiment'] = df['tweet'].apply(lambda x: sia.polarity_scores(x)[measurement])
# Creating a DF with the average sentiment score each day
sent_df = df.groupby('date')['sentiment'].mean().reset_index()
# Converting the dates to datetime
sent_df['date'] = sent_df['date'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d"))
return sent_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment