作者gene50814 (genechen)
看板Python
標題[問題]groupby 做邏輯判斷?
時間Sun May 3 16:46:50 2020
各位大大好
小弟有個時間序列的資料
範例如下:
https://i.imgur.com/1Z6Or19.jpg
小弟想做的事是要算每個月各公司市值的中位數 若公司大於等於中位數則新的column給
值’big’,反之則’small’
想完成的感覺如下圖:
https://i.imgur.com/1urJNVp.jpg
小弟想應該是要先把date groupby起來,但不知道該如何做後續的邏輯判斷
請各位大大指教了 謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.240.146.107 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1588495612.A.C6E.html
1F:推 yuasa: 你用pandas嗎?這兩個表除了多了B/S欄差在哪?你的B/S決定的 05/03 20:09
2F:→ yuasa: 條件是? 05/03 20:09
3F:推 TitanEric: 樓上你沒看內文齁 05/03 22:27
4F:→ gene50814: 是用pandas的 後來我是用join把groupby之後的series加 05/04 01:37
5F:→ gene50814: 到原本的df再做邏輯判斷 不知道有沒有更好的作法? 05/04 01:37
6F:推 moodoa3583: 如果是用data[B/S] = data[MarketValue].apply(lambda 05/04 12:52
7F:→ moodoa3583: x:True if x >np.median(data[MarketValue]) else Fa 05/04 12:52
8F:→ moodoa3583: lse) 呢? 05/04 12:52
9F:→ moodoa3583: *>= 05/04 12:53
10F:推 lycantrope: for date, tempdf in data.groupby("date"): 05/12 10:05
11F:→ lycantrope: BS = tempdf["Price"] > tempdf["Price"].median() 05/12 10:05
12F:→ lycantrope: df.loc[BS.index,"B/S"] = BS 05/12 10:06
13F:→ lycantrope: 打錯df改成date data.loc[BS.index,"BS"] = BS 05/12 10:06
14F:→ lycantrope: 把groupby 當iter for loop 判斷邏輯直接輸入data 05/12 10:07