python - pandas 中列的平均距离

标签 python pandas math

我有一个像这样的数据框:

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/

相关文章:

python - 正在解决试图在 DataFrame 的切片副本上设置值

python - Pandas :将系列的数据类型更改为字符串

javascript - Math.round(Math.random()) 组合似乎在我的 javascript 程序中生成了太多 0

找到最小 N 的算法,使得 N!可以被素数的幂整除

python - 如何将新的 json 对象插入现有的 json 文件(在对象中间)

python - 计算非升序字符串的最大值

python - 整个子图的颜色图

python - 曲线拟合为指数

python - 从 python 中的嵌套 URL 中抓取并解析表

python - 忽略 sympy 中的假想根