Pandas数据帧组内的计算

2024-04-25 17:18:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有熊猫数据帧如下所示。我要做的是,partition (or groupby) by BlockID, LineID, WordID,然后在每个组中使用current WordStartX - previous (WordStartX + WordWidth)来派生另一列,例如,WordDistance来表示这个单词和前一个单词之间的距离。在

这篇文章Row operations within a group of a pandas dataframe很有帮助,但在我的例子中涉及多个列(WordStartX和WordWidth)。在

 *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**

Tags: or数据距离bycurrent单词partitiongroupby
1条回答
网友
1楼 · 发布于 2024-04-25 17:18:11

diff()shift()函数通常有助于参考前一行或下一行的计算:

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

enter image description here

相关问题 更多 >