天天看點

pandas 前後行操作

問題:

各位老師好,我有一個dataframe 産品 資料1 資料2 A 1 2 B 4 5 C 6 3 我想找出比如這一行資料1>資料2 AND 資料1的上一行3 AND 4<5 則輸出 産品C 應該怎麼寫

回答:

說明:

選擇行的最快的方法不是周遊行。而是,建立一個mask(即,布爾數組),然後調用df[mask]選擇。 這裡有一個問題:如何動态表示dataframe中的目前行、前一行?答案是用shift。 shift(0):目前行 shift(1):前一行 shift(n):往前第n行 若要滿足多個條件 邏輯與&: mask = ((...) & (...)) 邏輯或|: mask = ((...) | (...)) 邏輯非~: mask = ~(...)

例如:

If I have the following dataframe: date A B M S 20150101 8 7 7.5 0 20150101 10 9 9.5 -1 20150102 9 8 8.5 1 20150103 11 11 11 0 20150104 11 10 10.5 0 20150105 12 10 11 -1 ... If I want to create another column 'cost' by the following rules:

currently, I am using the following function: def cost(df): if df[3]<0: return np.roll((df[2]-df[1]),1)df[3] elif df[3]>0: return np.roll((df[2]-df[0]),1)df[3] else: return 0 df['cost']=df.apply(cost,axis=0) Is there any other way to do it? can I somehow use pandas shift function in user defined functions? thanks.

答案: