2017-09-23 283 views
1

我有一个熊猫数据帧像创建从唯一的行值的新列:在大熊猫数据帧

yearPassed policyType count 
0  1990  1  2000 
1  1990  2  1400 
2  1990  3  1200 
3  1991  3  70 
4  1992  2  1000 
5  1992  3  800 

我想打一个柱状图,用的PolicyType列颜色编码,并显示在X轴上年并计入Y轴。

我试着这样做:

policy_vs_year.plot(x="yearPassed", y=["count", "policyType"], kind="bar") 
plt.show() 

但是这给出了一个非常糟糕情节。

所以我决定我的数据帧转换成这样的事情(也许更容易画出这样):

yearPassed  1  2  3 
0  1990  2000 1400  1200 
1  1991  0  0  70 
2  1992  0  1000  800 

我的问题是是否可以在熊猫初等函数来实现这一目标? (或有更简单的方法来绘制原始格式数据框 - 无需重新格式化吗?)

回答

2

这是使用df.pivot_table容易实现:

df = df.pivot_table(index=['yearPassed'], 
      columns=['policyType'], values='count').fillna(0) 
df 

policyType  1  2  3 
yearPassed       
1990  2000.0 1400.0 1200.0 
1991   0.0  0.0 70.0 
1992   0.0 1000.0 800.0 

此外,堆叠柱状图中可以使用由:

import matplotlib.pyplot as plt 
df.plot(kind='bar', stacked=True) 
plt.show() 

enter image description here

+0

谢谢,这是快速和正确的。我的数据从1850年到2015年有数年了。x轴变得混乱: [link](https://imgur.com/a/iN4m5) - 有什么办法呢?如果我想每隔20年分组一次,计数值是多少? –

+0

@AbhinandanDubey我认为你应该能够减少剧情上的蜱虫数量。例如,请参阅:https://stackoverflow.com/questions/6682784/how-to-reduce-number-of-ticks-with-matplotlib –

+0

@AbhinandanDubey至于你的第二个问题,我可以想出一些解决方案,但我不想给我一个没有数据的答案(我不确定我的答案是否正确,除非我确认)。你能开新的问题吗? –

2

只需使用pandas

df.set_index(['yearPassed','policyType']).unstack(-1).fillna(0).plot.bar(stacked=True) 

enter image description here