我有一个数据框“df”,其中包含以下数据:
State Text
0 California This is a beutiful day# It's too hard I am get...
1 Florida Can somebody please help me; I am new to python
2 New York But I am stuck with code How should I solve th...
Run Code Online (Sandbox Code Playgroud)
该数据框是使用以下代码从 csv 文件创建的:
delimiter = ' '
df = df2.groupby('State')['Text'].apply(lambda x: "%s" % delimiter.join(x)).reset_index()
Run Code Online (Sandbox Code Playgroud)
我需要对此数据框“df”状态进行情感分析(使用 TextBlob)。谁能帮我明智地进行情绪分析。我尝试这样做:
for row in df.itertuples():
text = df.iloc[:, 1].tolist()
tweets = " ".join(str(x) for x in text)
text = TextBlob(tweets)
score = text.sentiment
Run Code Online (Sandbox Code Playgroud)
但它给了我总数据帧的情绪分数,而不是每个州单独的情绪分数
我的代码输出为:
Sentiment(polarity=-0.07765151515151517, subjectivity=0.49810606060606055)
Run Code Online (Sandbox Code Playgroud)
但我希望分别输出每一行(这意味着每个州)的情绪输出。
您可以apply()与函数结合使用lambda。这是比循环更有效的方法。
df[['polarity', 'subjectivity']] = df['Text'].apply(lambda Text: pd.Series(TextBlob(Text).sentiment))
Run Code Online (Sandbox Code Playgroud)
这将返回:
State Text polarity subjectivity
0 California This is a beutiful day# It's too hard I am get -0.291667 0.541667
1 Florida Can somebody please help me; I am new to python 0.136364 0.454545
2 New York But I am stuck with code How should I solve th 0.000000 0.000000
Run Code Online (Sandbox Code Playgroud)