[英]how to replace an element of a 2-D numpy.array with a string in python?
我想在下一个条件下更改数组 2-D 的元素:如果元素> 100 将这个元素更改为单词“True”,否则更改单词的元素:“False”。 我试着去做,但我做不到。 我分享我做的下一个代码。 我希望你能帮助我。
import numpy as np
h1 =np.array([[10, 85, 103, 444, 150, 200, 35, 47],
[532, 476, 0, 1011, 50, 674, 5, 999],
[985, 7, 99, 101, 1, 58, 300, 78],
[750, 649, 86, 8, 505, 41, 745, 187]])
for r in range (0,len(h1)):
for c in range(0,len(h1[0])):
valor = h1[r][c]
if valor > 100:
h1[r][c] = 'True'
else:
h1[r][c] = 'False'
理论上输出应该是:
[[False, False, True, True, True, True, False, False],
[ True, True, False, True, False, True, False, True],
[ True, False, False, True, False, False, True, False],
[ True, True, False, False, True, False, True, True]]
你不需要循环, h1 = h1 > 100
就可以了
[[False False True True True True False False]
[ True True False True False True False True]
[ True False False True False False True False]
[ True True False False True False True True]]
如果您真的希望将值作为字符串使用astype(str)
h1 = (h1 > 100).astype(str)
为什么是for循环?! 当您的数组是numpy.array
。 你可以使用numpy.where
。 如果您有特定的字符串,您可以使用numpy.where
并设置您喜欢的任何字符串。
import numpy as np
h1 =np.array([[10, 85, 103, 444, 150, 200, 35, 47],
[532, 476, 0, 1011, 50, 674, 5, 999],
[985, 7, 99, 101, 1, 58, 300, 78],
[750, 649, 86, 8, 505, 41, 745, 187]])
# as Boolean : np.where(h1>100, True, False)
np.where(h1>100, 'True', 'False')
但是如果只有你想使用 'True' 或 'False' 你可以使用astype(str)
:
>>> (h1>100).astype(str)
array([
['False', 'False', 'True', 'True', 'True', 'True', 'False','False'],
['True', 'True', 'False', 'True', 'False', 'True', 'False','True'],
['True', 'False', 'False', 'True', 'False', 'False', 'True','False'],
['True', 'True', 'False', 'False', 'True', 'False', 'True','True']],
dtype='<U5')
你可以这样做:
h2 = []
for i in h1:
x = [True if x >100 else False for x in i]
h2.append(x)
但正如上述评论所提到的,还有更简单的方法。
I'mahdi 的解决方案是我想说的最好的解决方案,但如果你想继续在 for 循环中这样做:
它对您不起作用的原因是,您的 h1 是一个二维整数数组。 如果你改为说
h1 =np.array([[BLABLABLA]],dtype = object))
然后你可以改变你的阵列。 请注意,目前您正在使用字符串设置元素
"True"
而不是实际的布尔
True
所以我可能不会使用“”。 如果你想变得超酷并确保 h1 是一个布尔数组,我建议你也做一行说
h1 = h1.astype(bool)
希望这可以帮助。 如果您有任何问题,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.