计算 pandas 列中条目的频率,然后使用 X 轴字符串 labell 将它们绘制成图

Mar*_*abu 5 python plot bar-chart python-3.x pandas

我有以下熊猫专栏:

FuncGroup
ABC
ABC
ABC
ABC
BCD
BCD
BCD
SDS
SDS
ABC
BCD
SDS
BCD
Run Code Online (Sandbox Code Playgroud)

我想在熊猫数据框中获得这个预期的输出:

pd['FunctionGroup','FunctionCount']
ABC  4
BCD  5
SDS  3
Run Code Online (Sandbox Code Playgroud)

如何做到这一点,它是图形目的所必需的。

编辑 1:通过参考以下答案,我对原始代码进行了一些修改以使用 plotly 进行绘图。现在绘制了所有计数,但 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)
    #)
)
Run Code Online (Sandbox Code Playgroud)

Rah*_*wal 3

检查这是否适合您:

import pandas as pd
import plotly.plotly as py
Run Code Online (Sandbox Code Playgroud)

样本 df:

raw =pd.DataFrame({'FuncGroup':[
'ABC',
'ABC',
'ABC',
'ABC',
'BCD',
'BCD',
'BCD',
'SDS',
'SDS',
'ABC',
'BCD',
'SDS',
'BCD']})
Run Code Online (Sandbox Code Playgroud)

使用计数创建新的 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.
Run Code Online (Sandbox Code Playgroud)

创建绘图条形图:

py.iplot(new, filename='basic-bar')
Run Code Online (Sandbox Code Playgroud)