天天看點

Python機器學習小技巧:GroupBy 和 Shift實作 Pandas分組錯位

使用Pandas進行資料操作的時候,有時需要分組将資料錯位進行操作。

在資料分析中經常遇到需要分組使用a列的第n行資料與去b列的第n+1行資料進行對比或者計算的要求,下面是我使用pandas解決該問題的方法。首先要說的試這個問題可以通過操作Index來實作。不過Pandas針對這種情況已經提供了一種方法了,就是shift函數,用起來更加友善。shift函數定義如下:

pandas.DataFrame.shift

DataFrame.shift(self,periods=1,freq=None,axis=0,fill_value=None)[source]

Shift index by desired number of periods with an optional time freq.

When freq is not passed, shift the index without realigning the data. If freq is passed (in this case, the index must be date or datetime, or it will raise a NotImplementedError), the index will be increased using the periods and the freq.

比如我們要分析一個汽車的形式記錄,需要對比每個位置的前一個點和後一個點的情況,如下代碼即可:

df1['x_pre']=df1.groupby('CARID')['x'].shift(1)

df1['x_next']=df1.groupby('CARID')['x'].shift(-1)

df1['y_pre']=df1.groupby('CARID')['y'].shift(1)

df1['y_next']=df1.groupby('CARID')['y'].shift(-1)