一站式熊猫数据框搜索解决方案

时间:2020-01-17 16:13:14

标签: python pandas dataframe data-science

我想知道是否存在单行(或两行!)解决方案,而不是针对以下问题使用多个for循环:

如果它们是相同的$weight$ID$orient,我想计算任何$direct值之间的差:

$ID $spec   $view   $orient $direct $weight
9247    1   post    stance      0       2038.66 
9247    2   post    stance      15b     2177.74 
9247    4   post    stance      15f     1559.62 
9247    5   ant     stance      15b     2271.89     
9247    6   ant     stance      0       2075.44     
9247    7   ant     stance      15f     1438.31     
9247    8   post    fall        15a     1665.60     
9247    9   post    fall        15p     1742.82     
9119    1   ant     fall        0       994.48      
9119    2   ant     fall        15b     1081.44     
9119    3   post    fall        15b     1024.18 
9119    4   post    fall        0       1093.46 
9119    5   post    stance      15a     1220.13     
9119    6   post    stance      15p     1089.72     
9119    7   post    fall        15f     1056.21     

例如,应该计算第一行和第五行之间的差(2038.66-2075.44 = −36.78),依此类推,并写入这样的新数据帧:

$ID $orient $direct $weight-difference
9247    stance      0       −36.78  
9247    stance      15b     −94.15

谢谢!

1 个答案:

答案 0 :(得分:1)

series.diff与groupby一起使用:

px^2 + (py - d)^2 = (r1 + r2)^2
(py - d)^2 = (r1 + r2)^2 - px^2
d = py +/- Sqrt((r1 + r2)^2 - px^2) 

df.assign(difference=df.groupby(['$ID','$orient','$direct'])['$weight'].diff().mul(-1))
                                                                      .dropna()