关于使用 np.full 创建数组的 FutureWarning
FutureWarning on using np.full to create array
我使用以下代码在 python 中使用 numpy 创建了一个联系人数组。
import numpy as np
a = np.full((2,2), 7)
print(a)
它确实打印了预期的数组。
[[ 7. 7.]
[ 7. 7.]]
打印值后我也收到以下警告:
FutureWarning: in the future, full((2, 2), 7)
will return an array of dtype('int64')
.
谁能解释一下这是什么意思?这也是重要的还是可以忽略的(我们通常会发出警告 :P)。
我认为忽略这个 FutureWarning
是不明智的,因为到目前为止创建的 float
数组将来会更改为 int
数组。请注意,您指定了一个整数 7 作为填充值,但结果是一个浮点数组。我假设 numpy-developers 认为这种行为是不一致的,并希望在未来改变这种行为。
如果你想要一个 int
数组,你应该明确指定 dtype=int
:
>>> np.full((2, 2), 7, dtype=int)
array([[7, 7],
[7, 7]])
如果你想要一个 float
数组,只需将 7
更改为 float
:7.
:
>>> np.full((2, 2), 7.)
array([[ 7., 7.],
[ 7., 7.]])
也可以明确指定 dtype dtype=float
:
>>> np.full((2,2), 7, dtype=float)
array([[ 7., 7.],
[ 7., 7.]])
在所有三种情况下,FutureWarning
都消失了,无需明确忽略 FutureWarning
。
我不推荐它,但如果您不关心它是整数数组还是浮点数组并且不喜欢该警告,您可以明确禁止它:
import warnings
import numpy as np
with warnings.catch_warnings():
warnings.simplefilter('ignore', FutureWarning)
arr = np.full((2,2), 7)
我使用以下代码在 python 中使用 numpy 创建了一个联系人数组。
import numpy as np
a = np.full((2,2), 7)
print(a)
它确实打印了预期的数组。
[[ 7. 7.]
[ 7. 7.]]
打印值后我也收到以下警告:
FutureWarning: in the future,
full((2, 2), 7)
will return an array ofdtype('int64')
.
谁能解释一下这是什么意思?这也是重要的还是可以忽略的(我们通常会发出警告 :P)。
我认为忽略这个 FutureWarning
是不明智的,因为到目前为止创建的 float
数组将来会更改为 int
数组。请注意,您指定了一个整数 7 作为填充值,但结果是一个浮点数组。我假设 numpy-developers 认为这种行为是不一致的,并希望在未来改变这种行为。
如果你想要一个 int
数组,你应该明确指定 dtype=int
:
>>> np.full((2, 2), 7, dtype=int)
array([[7, 7],
[7, 7]])
如果你想要一个 float
数组,只需将 7
更改为 float
:7.
:
>>> np.full((2, 2), 7.)
array([[ 7., 7.],
[ 7., 7.]])
也可以明确指定 dtype dtype=float
:
>>> np.full((2,2), 7, dtype=float)
array([[ 7., 7.],
[ 7., 7.]])
在所有三种情况下,FutureWarning
都消失了,无需明确忽略 FutureWarning
。
我不推荐它,但如果您不关心它是整数数组还是浮点数组并且不喜欢该警告,您可以明确禁止它:
import warnings
import numpy as np
with warnings.catch_warnings():
warnings.simplefilter('ignore', FutureWarning)
arr = np.full((2,2), 7)