调查结果的条形图为pd.value_counts()

问题描述 投票:1回答:1

我进行了一项调查,答案可以是1-7,例如“绝对不开心”到“绝对快乐”以及介于两者之间的一切,数据是熊猫系列。在其上执行data.value_counts()会产生有序表

5.0  6
6.0  5
7.0  5
3.0  1
2.0  1

如何将其转换为条形图,其中a)存在7个条形,每个答案可能性为一条,b)按照1-7的顺序而不是根据大小排序和c)具有个别名称(非常不快乐,不快乐,部分不快乐) ,中性,部分快乐,快乐,非常快乐)而不是1-7的酒吧?谢谢!

python pandas plot survey
1个回答
1
投票

zip创建字典,由Index.mapreindex创建地图索引,用Series.plot.bar添加设置顺序添加缺失的catogories:

s = pd.Series([6,5,5,1,1], index=[5.0,6.0,7.0,3.0,2.0])

cats = ['extremely unhappy', 'unhappy', 'partly unhappy', 
        'neutral', 'partly happy', 'happy', 'extremely happy']
vals = range(1, 8)
d = dict(zip(vals, cats))

s.index = s.index.map(d.get)
s1 = s.reindex(cats, fill_value=0)
print (s1)
extremely unhappy    0
unhappy              1
partly unhappy       1
neutral              0
partly happy         6
happy                5
extremely happy      5
dtype: int64

s1.plot.bar()
© www.soinside.com 2019 - 2024. All rights reserved.