为了账号安全,请及时绑定邮箱和手机立即绑定

使用 numpy 的任务

使用 numpy 的任务

明月笑刀无情 2023-01-04 10:59:22
给出了一个大小为 5x5 的整数矩阵。用数字 0 替换此矩阵中第一行的所有负元素。我知道你需要循环遍历矩阵,但我不完全明白如何去做。请解释一下,因为我想学习如何解决此类问题。
查看完整描述

3 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

 import numpy as np

 #create matrix of size (5,5) with all zeros

 matrix = np.zeros((5,5))

 matrix[0]=[1,-2,3,-4,-5]

 matrix[0]=np.where(matrix[0]<0,0,matrix[0])

//img1.sycdn.imooc.com//63b4eba50001c4a502400206.jpg

说明:导入 numpy 后,初始化一个大小为 5x5 的 0 矩阵并分配一些值(+ve 和 -ve 都到第一行)。现在对矩阵的第一行使用 np.where() ,将 0 分配给 -ve 值和 +ve 值保持不变。np.where() 将第一个参数作为条件,第二个参数是如果条件为真时要做什么,否则当第三个参数中的条件为假时要做什么



查看完整回答
反对 回复 2023-01-04
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

让我们尝试通过示例来解决您的问题。


import numpy as np

#create matrix of size (5,5) with all zeros

matrix = np.zeros((5,5))

#since you are curious about first row, I will change the elements of the 1st row only

matrix[0][0] = 1

matrix[0][1] = -10

matrix[0][2] = 5

matrix[0][3] = -12

matrix[0][4] = -18

#loop through only the first row

for i in range(5):

#checking if number is negative

    if matrix[0][i] < 0:

        matrix[0][i] = 0


print(matrix)

应该这样做。


查看完整回答
反对 回复 2023-01-04
?
aluckdog

TA贡献1847条经验 获得超7个赞

“init_array”是你的 5x5 矩阵。

import numpy as np 
result = np.where(init_array[0]<0, 0, init_array[0])

必须初始化5x5矩阵的init_array

它将使用init_array[0]检查第一行元素,只要它小于零,然后它将用零替换它


查看完整回答
反对 回复 2023-01-04
  • 3 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信