2016-04-19 7 views
0

は、最初の列が日付で、連続した列が時間の経過と共に調整されるデータフレームがあると仮定します。 F.x.新しい情報が入手可能になると、特定の日付の風の予知は時間とともに変化します。Pandaのdiff()をdata.frameの最初の列/行に対して使用します。

私の仕事は、の最初のの列についての違いを計算することです。 原則はpandas.DataFrame.diffに似ていますが、参照値は前の列ではなく、常に最初の列です。

だからあなたのデータフレームは、この

Date Forecast1 Forecast2 Forecast3   
1/1/15 5    3    7 

のように見えると仮定すると、私は結果は次のようになりたい:

Date Forecast1 Forecast2 Forecast3   
1/1/15 NaN    -2   2 

私は私の説明が明確だった願っています。

ありがとうございました。

答えて

2

だけ使用pd.DataFrame.sub

In [108]: df=pd.DataFrame(np.random.randint(0,6,(3,3)), 
columns=['Forecast'+str(i) for i in range(1,4)], 
index=pd.date_range('2016/1/1',periods=3)) 

In [109]: df 
Out[109]: 
      Forecast1 Forecast2 Forecast3 
2016-01-01   5   5   5 
2016-01-02   0   3   0 
2016-01-03   2   4   2 

In [110]: df.sub(df.Forecast1,axis=0) 
Out[110]: 
      Forecast1 Forecast2 Forecast3 
2016-01-01   0   0   0 
2016-01-02   0   3   0 
2016-01-03   0   2   0 
0

あなたが行にそれを適用する代わりに、列の(軸= 1)apply(..., axis=1)を使用してそれを行うことができます(デフォルト:軸= 0):

In [78]: df 
Out[78]: 
    Date Forecast1 Forecast2 Forecast3 
0 1/1/15   5   3   7 
1 2/3/15   1   4   5 
2 3/4/15   10   2   1 

In [79]: cols = [c for c in df.columns.tolist() if 'Forecast' in c] 

In [80]: cols 
Out[80]: ['Forecast1', 'Forecast2', 'Forecast3'] 

In [81]: df[cols].apply(lambda x: x-x[0], axis=1) 
Out[81]: 
    Forecast1 Forecast2 Forecast3 
0   0   -2   2 
1   0   3   4 
2   0   -8   -9 
関連する問題