Calculation within Pandas dataframe group

我只是一个虾纸丫 提交于 2021-01-29 02:32:21

问题


I've Pandas Dataframe as shown below. What I'm trying to do is, partition (or groupby) by BlockID, LineID, WordID, and then within each group use current WordStartX - previous (WordStartX + WordWidth) to derive another column, e.g., WordDistance to indicate the distance between this word and previous word.

This post Row operations within a group of a pandas dataframe is very helpful but in my case multiple columns involved (WordStartX and 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**

回答1:


The diff() and shift() functions are usually helpful for calculation referring to previous or next rows:

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



来源:https://stackoverflow.com/questions/40493829/calculation-within-pandas-dataframe-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!