gpt4 book ai didi

Python 尝试更新 2D numpy 数组中的值,但值不会更新

转载 作者:行者123 更新时间:2023-12-04 09:31:54 27 4
gpt4 key购买 nike

对不起,我是一个 python 菜鸟。
我一直试图在表示 x,y 值的二维数组中找到最大值。
然后应将最大值替换为 0 并绘制。但是,我尝试了很多方法来替换该值,但无法替换该值。
到目前为止我的代码是

m2= [ [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] , [ 0 , 1 , 2 , 3 , 2 , 1 , 0 , 1 , 2 , 3 ]]

a2 = np.array(m2, dtype=np.int)

plt.plot(a2[0,:], a2[1,:], 'r-x')

a2maxy = np.max(a2[1,:])
print("a2 y values: ", a2[1,:])

for y in (a2[1,:]):
if (y==a2maxy):
print(y)
print("max found ", y)
y=0
print(y)
但是我的输出(显示最大 y 值不变是
a2 y values:  [0 1 2 3 2 1 0 1 2 3]
3
max found 3
0
3
max found 3
0
[[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 2 1 0 1 2 3]]

最佳答案

我认为您的问题是您实际上并未引用要在 for 中编辑的值数组环形。可能有一种更巧妙的方法可以做到这一点,但您可以使用 enumerate 做您想做的事情作为 for 中的迭代器循环,然后引用 a2 中的项目你关心的数组,像这样:

import numpy as np
from matplotlib import pyplot as plt
m2= [ [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] , [ 0 , 1 , 2 , 3 , 2 , 1 , 0 , 1 , 2 , 3 ]]

a2 = np.array(m2, dtype=np.int)

plt.plot(a2[0,:], a2[1,:], 'r-x')

a2maxy = np.max(a2[1,:])
print("a2 y values: ", a2[1,:])

for idx,y in enumerate(a2[1,:]):
if (y==a2maxy):
print("max found ", y)
a2[1,idx]=0

print("new a2 y values: ", a2[1,:])
现在输出是:
a2 y values:  [0 1 2 3 2 1 0 1 2 3]
max found 3
max found 3
new a2 y values: [0 1 2 0 2 1 0 1 2 0]

关于Python 尝试更新 2D numpy 数组中的值,但值不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62804293/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com