2017-03-06 199 views
1

列平均列在大熊貓0.18.1,蟒蛇2.7.6:蟒蛇大熊貓計算由

假設我們有如下表:

ID,FROM_YEAR,FROM_MONTH,YEARMONTH,AREA,AREA2 
1,2015,1,201501,200,100 
1,2015,2,201502,200,100 
1,2015,3,201503,200,100 
1,2015,4,201504,200,100 
1,2015,5,201505,200,100 
1,2015,6,201506,200,100 
1,2015,7,201507,200,100 
1,2015,8,201508,200,100 
1,2015,9,201509,200,100 
1,2015,10,201510,200,100 
1,2015,11,201511,200,100 
1,2015,12,201512,200,100 
1,2016,1,201601,100,200 
1,2016,2,201602,100,200 
1,2016,3,201603,100,200 
1,2016,4,201604,100,200 
1,2016,5,201605,100,200 
1,2016,6,201606,100,200 
1,2016,7,201607,100,200 
1,2016,8,201608,100,200 
1,2016,9,201609,100,200 
1,2016,10,201610,100,200 
1,2016,11,201611,100,200 
1,2016,12,201612,100,200 

有沒有什麼辦法,我們可以做同樣的事情作爲在python熊貓中的以下MySQL查詢(合併功能可能可以工作,但有什麼辦法可以避免昂貴的合併/連接在Python熊貓)?

SELECT 
ID, 
FROM_YEAR, 
'A' AS TYPE, 
AVG(AREA) AS AREA, 
AVG(AREA2) AS AREA2 
FROM table GROUP BY ID,FROM_YEAR 

UNION ALL 

SELECT 
ID, 
FROM_YEAR, 
'B' AS TYPE, 
AVG(AREA) AS AREA, 
AVG(AREA2) AS AREA2 
FROM table GROUP BY ID,FROM_YEAR; 

這裏的目標是獲得在以下格式的歷年平均面積和AREA2列:

ID,FROM_YEAR,TYPE,AREA,AREA2 
1,2015,A,200,100 
1,2016,A,100,200 
1,2015,B,200,100 
1,2016,B,100,200 

可以在任何大師指教?

=================================一個擴展問題========== =======

感謝您的回答!我只是遇到一個連續12個案例的另一個問題:

所需的輸出:

ID,FROM_YEAR,FROM_MONTH,YEARMONTH,AREA,AREA2 
1,2015,1,201501,NULL,NULL 
1,2015,2,201502,NULL,NULL 
1,2015,3,201503,NULL,NULL 
1,2015,4,201504,NULL,NULL 
1,2015,5,201505,NULL,NULL 
1,2015,6,201506,NULL,NULL 
1,2015,7,201507,NULL,NULL 
1,2015,8,201508,NULL,NULL 
1,2015,9,201509,NULL,NULL 
1,2015,10,201510,NULL,NULL 
1,2015,11,201511,NULL,NULL 
1,2015,12,201512,200,100 

下面的代碼

agg=df.groupby(['ID','FROM_YEAR'])[['AREA','AREA2']].rolling(window=12).mean() 

纔會產生這樣的結果,其中FROM_MONTH和YEARMONTH失蹤。

ID,FROM_YEAR,AREA,AREA2 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,NULL,NULL 
1,2015,200,100 

任何人都可以啓發?謝謝!

回答

3

您可以使用pandas.concat這裏只涉及一個聚集和不調用merge/join過程:用`assign`和`concat`

agg = df.groupby(['ID', 'FROM_YEAR'], as_index=False)[["AREA", "AREA2"]].mean() 

pd.concat([agg.assign(TYPE = t) for t in ["A", "B"]], ignore_index=True) 

enter image description here

+0

列表理解的尼斯使用得到這裏的類型欄! +1 – pansen

+0

@pansen謝謝!欣賞評論。 – Psidom

+0

感謝您的優雅的答案,Psidom!關於如何添加另一列並更新問題,我還有一個問題。你能開導嗎? – Chubaka