我有以下資料框
Line emotion
0 d... anger
1 a ... shame
2 b... sadness
3 c... joy
4 d... shame
... ... ...
117 f... joy
118 g... disgust
119 h... disgust
120 i... fear
121 j anger
我需要用這樣的情緒畫一個雷達:
import numpy as np
import matplotlib.pyplot as plt
categories = ['Joy', 'Fear', 'Anger', 'Sadness', 'Disgust', 'Shame','Guilt']
q1 = [4, 4, 5, 4, 3, 7, 10]
label_loc = np.linspace(start=0, stop=2*np.pi, num=len(q1) 1)[:-1]
plt.figure(figsize=(8, 8))
plt.subplot(polar=True)
plt.plot(label_loc, q1, label='q 1')
plt.title('Answer to Question 1 - Emotion Analysis', size=20)
lines, labels = plt.thetagrids(np.degrees(label_loc), labels=categories)
plt.legend()
plt.show()
結果是:

我的問題是,如何輕松地將 pandas 資料框轉換為每種特定情緒的 COUNTS 陣列:
q1 = [4, 4, 5, 4, 3, 7, 10]
其中每個數字代表這些情緒:
categories = ['Joy', 'Fear', 'Anger', 'Sadness', 'Disgust', 'Shame','Guilt']
uj5u.com熱心網友回復:
用于Series.value_counts將值和索引轉換為串列:
s = df['emotion'].value_counts()
q1 = s.to_list()
categories = s.index.tolist()
print (q1)
[2, 2, 2, 2, 1, 1]
print (categories)
['joy', 'anger', 'shame', 'disgust', 'sadness', 'fear']
如果排序很重要,則將值轉換為小寫并添加Series.reindex:
categories = ['Joy', 'Fear', 'Anger', 'Sadness', 'Disgust', 'Shame','Guilt']
cats = [x.lower() for x in categories]
q1 = df['emotion'].value_counts().reindex(cats, fill_value=0).tolist()
print (q1)
[2, 1, 2, 1, 2, 2, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461699.html
標籤:Python 熊猫 麻木的 matplotlib
