2017-09-23 390 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