I have a very basic question in numpy arrays:
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. Please help.
2 Answers 2
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"
Comments
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). if your arrays are numpy arrays then this is the way they are represented (printed). 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 ]
numpytag? these are notnumpyarrays.