用随机索引的NaN值创建2D数组的最佳方法是什么?

时间:2019-01-30 12:08:34

标签: arrays python-3.x numpy

以下两种方法都创建一个二维数组,其NaN值位于随机索引处。有某种捷径可以做到这一点吗?

import numpy as np

# approach 1
arr1 = np.random.randint(1,11,(5,5)).astype('float')
for rows, cols in [arr1.shape]:
    i_rows = np.random.randint(0, rows, 5)
    i_cols = np.random.randint(0, cols, 5)
arr1[i_rows, i_cols] = np.nan

# approach 2
arr2 = np.random.randint(1, 11, 25).astype('float')
for i in np.random.randint(0, arr2.size, 5):
    arr2[i] = np.nan
arr2 = arr2.reshape((5,5))

1 个答案:

答案 0 :(得分:4)

这是一种实现方法:

import numpy as np

np.random.seed(100)
# Make input
arr1 = np.random.randint(1, 11, (5, 5)).astype('float')
# Select five indices from the whole array
idx_nan = np.random.choice(arr1.size, 5, replace=False)
# "Unravel" the indices and set their values to NaN
arr1[np.unravel_index(idx_nan, arr1.shape)] = np.nan
print(arr1)

输出:

[[ 9.  9.  4.  8.  8.]
 [ 1.  5.  3.  6.  3.]
 [ 3. nan nan nan  9.]
 [ 5.  1. 10.  7.  3.]
 [ 5. nan  6.  4. nan]]