gpt4 book ai didi

python - Pandas 数据框搜索的单行解决方案

转载 作者:行者123 更新时间:2023-12-01 06:33:19 25 4
gpt4 key购买 nike

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

我想计算任何 $weight 值之间的差异,如果它们针对相同的 $ID$orient$直接:

$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

谢谢!

最佳答案

使用series.diff与分组:

df.assign(difference=df.groupby(['$ID','$orient','$direct'])['$weight'].diff().mul(-1))
.dropna()
<小时/>
     $ID  $spec $view $orient $direct  $weight  difference
3 9247 5 ant stance 15b 2271.89 -94.15
4 9247 6 ant stance 0 2075.44 -36.78
5 9247 7 ant stance 15f 1438.31 121.31
10 9119 3 post fall 15b 1024.18 57.26
11 9119 4 post fall 0 1093.46 -98.98

关于python - Pandas 数据框搜索的单行解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59791046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com