简体   繁体   English

如何在Numpy Python中替换数组中的值

[英]How to replace a value in array in numpy python

I have a very basic question in numpy arrays: 我在numpy数组中有一个非常基本的问题:

My array looks something like this: 我的数组看起来像这样:

Array = [["id1", "1.0"],["id2", "0.0"]] 

I want to read the second element of the array and replace with an another character. 我想读取数组的第二个元素并替换为另一个字符。 Its like 就像是

for i in range(0,len(array)):
    if array[i] == "0.0":
        array[i] = "ClassA"
    else
        array[i] = "ClassB"

How to achieve this. 如何实现这一目标。 I am not able to read "0.0" or "1.0" correctly. 我无法正确读取“ 0.0”或“ 1.0”。 Please help. 请帮忙。

You have two arrays inside an array. 数组中有两个数组。 The below code should work: 下面的代码应该工作:

array = [["id1", "1.0"],["id2", "0.0"]]

for item in array:
    if item[1] == "0.0":
        item[1] = "ClassA"
    else:
        item[1] = "ClassB"

you are missing , s in the definition of your array. 你缺少,在你定义数组。 your array is the same as this: [["id11.0"], ["id20.0"]] (strings just get concatenated). 您的数组与此相同: [["id11.0"], ["id20.0"]] (字符串只是串联在一起)。 if your arrays are numpy arrays then this is the way they are represented (printed). 如果您的数组是numpy数组,则这就是它们表示(打印)的方式。 but that does not work as input... 但这不能作为输入...

starting from your code you could to this: 从您的代码开始,您可以这样做:

array = [["id1", "1.0"], ["id2", "0.0"]]

for i, (id_, number) in enumerate(array):
    if number == "0.0":
        array[i] = [id_, "ClassA"]
    else:
        array[i] = [id_, "ClassB"]

or, more elegant, use a list-comprehension: 或者,更优雅的是,使用列表理解:

array = [[id_, "ClassA"] if number == "0.0" else [id_, "ClassB"]  
         for id_, number in array ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM