【问题标题】:Substitute labels of bar plot in PandasPandas中条形图的替代标签
【发布时间】:2018-04-18 22:01:08
【问题描述】:

我有一个 pandas 数据框,我正在使用以下方法在一个特定列(“question_1”)上绘制条形图:

df1.question_1.value_counts().plot(kind='bar', rot=0)

这很好用。 value_counts() 方法返回以下系列:

4  30
3  20
5  15
2  10

第一列然后用作条的标签,第二列是条的高度。

现在我有另一个数据帧 df2,其中包含第一个数据帧 df1 的 question_1 列中的值的编码:

ID  value
1   "test1"
2   "test2"
3   "test3"
4   "test4"
5   "test5"

现在我想将此编码用于 value_counts() 的结果:

"test4"  30
"test3"  20
"test5"  15
"test2"  10

最后,我的目标是用这些编码替换条形图的标签(即,我希望将“test4”作为标签而不是 4)。也许这也可以通过更简单的方式完成。

【问题讨论】:

    标签: python pandas bar-chart


    【解决方案1】:

    IIUC,

    您可以将由值计数产生的系列索引映射到新索引:

    s 是 value_counts 的结果:

    s = pd.Series([30,20,15,10],index=[4,3,5,2])
    

    还有绘图:

    df2 是您的“编码数据帧”:

    df2 = pd.DataFrame({'ID':[1,2,3,4,5],'value':['test1','test2','test3','test4','test5']})
    

    让我们使用以下方法将 s.index 映射到 df2 值:

    s.index = s.index.to_series().map(df2.set_index('ID')['value'])
    

    然后,现在开始绘制。

    s.plot(kind='bar', rot=0)
    

    输出:

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-01-22
      • 1970-01-01
      相关资源
      最近更新 更多