Pandas dataframe hist未绘制类别变量

2024-04-19 23:07:10 发布

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

我有一个数据帧,我想在其中绘制每列的直方图。在

df_play = pd.DataFrame({'a':['cat','dog','cat'],'b':['apple','orange','orange']})
df_play['a'] = df_play['a'].astype('category')
df_play['b'] = df_play['b'].astype('category')

df_play
df_play.hist(layout = (12,10))

但是我得到了ValueError: num must be 1 <= num <= 0, not 1 当我尝试在值中使用整数而不是category时,它工作得很好,但我确实希望唯一字符串的名称位于x轴上。在


Tags: 数据appledataframedfplay绘制直方图num
3条回答

由于没有用于binning的自然参数,也许您想要的不是直方图而是每个Seriesvalue counts条形图?如果是这样,你可以通过

df_play['a'].value_counts().plot(kind='bar')

Example bar plot

我意识到这样做的一种方法是首先指定fig和axs,然后遍历我们想要绘制值计数的数据帧的列名。在

fig, axs = plt.subplots(1,len(df_play.columns),figsize(10,6))
for i,x in enumerate(df_play.columns):
    df_play[x].value_counts().plot(kind='bar',ax=axs[i])

enter image description here

您只需在列和绘图之间应用pd.value_counts。在

>>> df_play.apply(pd.value_counts).T.stack().plot(kind='bar')

enter image description here

如果您想要合适的子批次或更复杂的东西,我建议您使用value_counts迭代并自己创建子批次。在

相关问题 更多 >