计算pandas列中条目的频率,然后用X轴string lab绘图

2024-06-23 20:10:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下熊猫专栏:

FuncGroup
ABC
ABC
ABC
ABC
BCD
BCD
BCD
SDS
SDS
ABC
BCD
SDS
BCD

我想在pandas dataframe中得到这个预期输出:

^{pr2}$

如何做到这一点,这是图形需要的。在

编辑1: 通过参考下面的答案,我对原始代码做了一些修改 用绘图绘制。现在所有的计数都被绘制出来了,但是X轴的标签没有用这个方法来显示,这就是我希望标签和计数存储在pd中的原因。在

参考代码

otrace1 =go.Bar(
    #x=stock_opt_pe.index
    x=datalist['Function group'].nunique(),
    y=datalist['Function group'].value_counts(),
    text=datalistFg, # dont know what to give here to get a X axis label
    textposition = 'auto',
    #xaxis-type (enumerated: “-” | “linear” | “log” | “date” | “category” )
    #xaxis-type (enumerated: “-” | “linear” | “log” | “date” | “category” )
    #name='Function Group Vx RespPerson',
    #orientation = 'v',
    #marker = dict(
        #color = 'rgba(224, 224, 224, 0.6)',
        #line = dict(
            #color = 'rgba(246, 250, 206, 1.0)',
            #color = 'rgb(60, 60, 60)',
            #width = 0)
    #)
)

Tags: to代码typegroup绘制function标签color
2条回答

您可能正在查找值计数,这类似于collections counter。在

df['FuncGroup'].value_counts()

对于打印,请看以下示例:

^{pr2}$
dfout = df['FuncGroup'].value_counts().reset_index()
print(dfout)

#  index  FuncGroup
#0   ABC          2
#1   BCD          1

退货:

enter image description here

检查这是否适合您:

import pandas as pd
import plotly.plotly as py

样品df:

^{pr2}$

创建具有计数的新df:

s = raw['FuncGroup'].value_counts() ## Counts the occurrence of unqiue elements and stores in a variable called "s" which is series type
new = pd.DataFrame({'FuncGroup':s.index, 'Count':s.values})  ## Converting series type to pandas df as plotly accepts dataframe as input. The two columns of df is FuncGroup which is being made by index of series and new variable called count which is made by values of series s.

绘制条形图:

py.iplot(new, filename='basic-bar')

相关问题 更多 >

    热门问题