[英]Pandas groupby two columns and create a plot of count totals
我是Pandas的新手,我正在尋找一種方法來繪制按兩列分組的數據。 這是我的例子:
首先,我按“日期”(年份)和“主要類型”列進行分組。
groups = df.groupby([df['Date'].map(lambda x: x.year), pri_type['Primary Type']])
從那以后,我可以獲得一系列基本上我想要繪制的內容。
groups.size().head()
Date Primary Type
2001 ARSON 1010
ASSAULT 31384
BATTERY 93448
BURGLARY 26011
CRIM SEXUAL ASSAULT 1794
dtype: int64
但是當我繪制這個時,我會得到一個非常混亂的情節,在x軸上有數千個標簽。 我想得到的是x軸上有日期的圖和帶有所有主要類型的ledgend。 與此圖類似的東西:
提前致謝!
你希望在x軸上顯示什么,日期? 如果是這樣,您可以將日期設置為索引:groups.set_index('Date')
我想出的解決方案是將系列轉換為數據框並使用unstack()方法。 這是我做的:
# convert to a dataframe
df = groups.size().to_frame()
| | | 0
|------ | --------------|------
|Date | Primary Type |
| | ARSON | 1010
| | ASSAULT | 31384
| 2001 | BATTERY | 93234
| | BURGLARY | 26031
| | CRIM SEXUAL AS| 1723
# unstack() to pivot the data which puts it in the correct format for plot()
df.unstack(level=-1)
| |0
|------------|-------|---------|-------...
|Primary Type|ARSON |ASSAULT |BATTERY...
|Date | | | ...
|2001 |1010.0 |31384.0 |93234.0...
|2002 |2938.0 |31993.0 |94235.0...
|2003 |955.0 |30082.0 |92834.0...
除了0之外,這幾乎是我所追求的圖形,但我可以擺脫它。 正如你所看到它仍然不是很易讀,但這解決了我如何繪制圖形的問題。
df.unstack(level=-1).plot(kind='bar', figsize = (10,10))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.