0

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.

asked Aug 16, 2017 at 9:22
4
  • 2
    why the numpy tag? these are not numpy arrays. Commented Aug 16, 2017 at 9:24
  • @hiroprotagonist - I am sorry if that is the case, the element type is numpy.ndarray. Is this and the numpy arrays are different? And checked for the dtype of the element - it is "str18912". Commented Aug 16, 2017 at 9:28
  • 2
    ["id1" "1.0"] don't they have comma between them?? Commented Aug 16, 2017 at 9:32
  • 1
    @PrakashPalnati - Thank you for pointing me out the mistake. I have updated the question. Commented Aug 16, 2017 at 10:01

2 Answers 2

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"
answered Aug 16, 2017 at 9:30
Sign up to request clarification or add additional context in comments.

Comments

1

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 ]
answered Aug 16, 2017 at 9:32

1 Comment

Protagnoistn - Thank you very much for the response. This also has worked for me.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.