2016-11-08 18 views
1

私はPandas Dataframeを以下のように見ました。私がしようとしているのは、partition (or groupby) by BlockID, LineID, WordIDです。そして、各グループ内でcurrent WordStartX - previous (WordStartX + WordWidth)を使用して、この単語と前の単語の間の距離を示す別の列、たとえばWordDistanceを派生させます。Pandasデータフレームグループ内の計算

この投稿Row operations within a group of a pandas dataframeは非常に役に立ちますが、私の場合は複数の列(WordStartXとWordWidth)が関わっています。

diff()shift()機能は通常、前または次の行を参照する計算に役立つ
*BlockID LineID WordID WordStartX WordWidth  WordDistance 
0  0  0  0   275  150     0 
1  0  0  1   431   96 431-(275+150)=6   
2  0  0  2   642   90 642-(431+96)=115 
3  0  0  3   746  104 746-(642+90)=14 
4  1  0  0   273   69   ... 
5  1  0  1   352  151   ... 
6  1  0  2   510   92 
7  1  0  3   647   90 
8  1  0  4   752  105** 

答えて

1

:あなたの迅速な対応のための

df['WordDistance'] = (df.groupby(['BlockID', 'LineID']) 
     .apply(lambda g: g['WordStartX'].diff() - g['WordWidth'].shift()).fillna(0).values) 

enter image description here

+0

おかげ@Psidom - あなたのソリューションが動作するだけでなく、簡潔でエレガント! – renjl0810

関連する問題