Python 涉及浮点数和整数的弃用警告

Python deprecation warning involving floats and integers

我想 select 一个大数组的一小部分,并找到该子集的平均值。我在定义子集时尝试指定整数:

import numpy as np

x = np.linspace(-10,10,1e6) # whole dataset

x0 = x[int(len(x)//2-5):int(len(x)//2+5)] # subset
print(x0)
xm = np.mean(x0) # average value of data subset
print(xm)

但我的代码给出了一个弃用警告:

DeprecationWarning: object of type <class 'float'> cannot be safely interpreted as an integer.
  x = np.linspace(-10,10,1e6)

有没有更好的方法计算数据子集的平均值?我应该如何处理这个警告,它会成为新版本 Python 中的问题吗?我正在使用 Spyder 3.2.8。

问题是 np.linspace 期望它应该产生的点数作为它的第三个参数。因此,这应该是一个整数(整数)。但是 1e6 被解析为浮点数,因此需要转换为整数,因此出现警告。

解决办法是把1e6写成一个整数,1000000。如果你使用 Python 3,你可以写 1_000_000 来使数字更易读。