我有一个像这样的数据框:
sample = pd.DataFrame({'a': [10, 16, 7, 2, 5]})
如何找到“a”列的平均距离?例如,10 和 16 之间的平均距离 = (10 + 6)/2 = 8
最佳答案
经过你描述的数学运算后,它相当于“下一个值除以 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
关于python - pandas 中列的平均距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67969106/