【问题标题】:Create a bar plot in pandas with dates on x-axis, one bar for each value in other column在 pandas 中创建一个条形图,x 轴为日期,另一列中的每个值一个条形图
【发布时间】:2017-12-07 13:33:53
【问题描述】:

我有以下熊猫数据框:

>>> df
>>> StartDate         Port  Count
2011-08-10 11:07:10   3128  10
2011-08-10 11:07:40     80   1
2011-08-10 11:07:40    443   1
2011-08-10 11:07:40   3128  10
2011-08-10 11:08:00    443   1
2011-08-10 11:08:00   3128   9
2011-08-10 11:08:20     80   1

我想创建一个直方图,其中 x 轴为“StartDate”期间,y 轴为计数,“端口”列中的每个值对应一列。

我尝试将 groupby() 与 df.plot.bar() 一起使用,但它没有给我想要的结果。我该怎么办?

好的,不是最好的绘图,但应该给出想法。 y 轴是一个计数,每个条形代表“端口”列中的值。 x 轴上是第一列的日期

【问题讨论】:

  • 你能做一个模拟绘图并将其链接到这里吗?以目前的形式,这个问题很难理解。
  • 我用草图更新了。

标签: python pandas


【解决方案1】:

我相信您需要set_index + unstack 进行整形和最后使用DataFrame.plot.bar

df1 = df.set_index(['StartDate','Port'])['Count'].unstack(fill_value=0)
print (df1)
Port                 80    443   3128
StartDate                            
2011-08-10 11:07:10     0     0    10
2011-08-10 11:07:40     1     1    10
2011-08-10 11:08:00     0     1     9
2011-08-10 11:08:20     1     0     0

df1.plot.bar()

pivot 的替代解决方案:

df1 = df.pivot(index='StartDate', columns='Port', values='Count')
print (df1)
Port                 80    443   3128
StartDate                            
2011-08-10 11:07:10   NaN   NaN  10.0
2011-08-10 11:07:40   1.0   1.0  10.0
2011-08-10 11:08:00   NaN   1.0   9.0
2011-08-10 11:08:20   1.0   NaN   NaN

df1.plot.bar()

【讨论】:

  • 谢谢。但这并不是我想要的。对不起,我描述得很糟糕
  • 请立即查看解决方案。
  • 是的,这正是我想要的。非常感谢!
  • 很高兴能帮上忙!祝你好运!
猜你喜欢
  • 2020-01-02
  • 2019-03-20
  • 2020-09-18
  • 2018-09-18
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-21
相关资源
最近更新 更多