【发布时间】:2020-01-17 16:13:14
【问题描述】:
我想知道是否有一个(或两个!)解决方案,而不是使用多个 for 循环来解决以下问题:
如果 $ID、$orient 和 $direct 相同,我想计算任何 $weight 值之间的差异:
$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)等等,写在这样一个新的dataframe中:
$ID $orient $direct $weight-difference
9247 stance 0 −36.78
9247 stance 15b −94.15
谢谢!
【问题讨论】:
-
到目前为止你有什么尝试?
-
你想用单线创建所有对吗?
-
类似:
df.assign(difference=df.groupby(['$ID','$orient','$direct'])['$weight'].diff().mul(-1)).dropna()? -
我一直在测试 df.groupby(['$ID', '$orient', '$direct'], as_index=False)...
-
@anky_91,在回答部分写下你的解决方案,它会比评论更有帮助。
标签: python pandas dataframe data-science