numpy 我试图从10*3矩阵中删除随机值,使其成为10 *2矩阵

oipij1gg  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(96)

生成10*3矩阵的原代码

random_values = np.round(np.random.normal(mean, std_deviation, (num_rows, num_columns)), 
2)
b_values = np.sort(random_values, axis=1)[:, ::-1]
weights = np.array([0.2, 0.5, 0.3])
y_values = np.round(np.dot(b_values, weights), 2)

从原始矩阵中删除随机值

def drop_random_value(matrix):
    for i in range(matrix.shape[0]):
    # Get a random index within the row
    random_index = np.random.randint(matrix.shape[1])
    
    # Set the value at the random index to NaN
    matrix[i, random_index] = np.nan

从B_values中删除随机值

drop_random_value(b_values)

   print("Modified b_values:")
   print(b_values)

Expected Output:
[[0.93  0.12 ]
 [0.4   0.4  ]
 [0.64  0.23 ]
 [0.56  0.56 ]
 [0.44  0.41 ]
 [0.55  0.55 ]
 [0.52  0.23 ]
 [0.69  0.69 ]
 [0.62  0.405]
 [0.71  0.53 ]]

Actual Output:[[0.93    nan 0.12 ]
               [  nan 0.4   0.4  ]
               [0.64    nan 0.23 ]
               [0.56  0.56    nan]
               [0.44  0.41    nan]
               [0.55  0.55    nan]
               [  nan 0.52  0.23 ]
               [0.69  0.69    nan]
               [0.62  0.405   nan]
               [  nan 0.71  0.53 ]]

你能帮助我达到预期的产量吗

cedebl8k

cedebl8k1#

IIUC,您可以:

def drop_random_value(matrix):
    for i in range(matrix.shape[0]):
        random_index = np.random.randint(matrix.shape[1])
        matrix[i, random_index] = np.nan

    return matrix[~np.isnan(matrix)].reshape((matrix.shape[0], matrix.shape[1] - 1))

b_values = drop_random_value(b_values)
print(b_values)

如果b_values为:

[[ 0.2  -0.02 -0.09]
 [ 0.08  0.07 -0.1 ]
 [ 0.06  0.05 -0.  ]
 [ 0.25  0.1  -0.06]
 [ 0.08 -0.04 -0.07]
 [-0.03 -0.06 -0.11]
 [ 0.04 -0.02 -0.2 ]
 [-0.04 -0.07 -0.15]
 [ 0.07  0.   -0.03]
 [ 0.05 -0.01 -0.09]]

然后在通话后:

[[-0.02 -0.09]
 [ 0.08  0.07]
 [ 0.06  0.05]
 [ 0.25 -0.06]
 [ 0.08 -0.07]
 [-0.06 -0.11]
 [ 0.04 -0.02]
 [-0.07 -0.15]
 [ 0.07 -0.03]
 [ 0.05 -0.01]]

相关问题