我有一个这样的数据框:
sample = pd.DataFrame({'a': [10, 16, 7, 2, 5]})
如何找到“a”列的平均距离?比如10到16之间的平均距离=(10+6)/2=8
答案 0 :(得分:1)
x 和 y 的“平均距离”定义为 (x + (y - x))/2。
这只是 y/2。删除第一行并将其余行除以 2:sample.a[1:]/2
答案 1 :(得分:1)
经过你描述的数学运算,相当于“下一个值除以2”。所以我们通过移动系列获得下一个值,然后 / 2
将它们减半:
# data itself
>>> sample
a
0 10
1 16
2 7
3 2
4 5
# shift the values upwards by 1 unit so 2nd becomes 1st etc.
# and the last becomes NaN as there is nothing below it to replace
>>> sample.shift(-1)
a
0 16.0
1 7.0
2 2.0
3 5.0
4 NaN
# per your formula
>>> sample.shift(-1) / 2
a
0 8.0
1 3.5
2 1.0
3 2.5
4 NaN