0

I want to change multiple array values from numeric to strings based on the condition that values greater than 70 will become 'P' while values less than 70 will become 'F'. For example: [20,80,30,100] should become ['F','P','F','P'] and [50,60,90,45] should become ['F','F','P','F'].

Current code:

def grade(input_array):
    a = len(input_array)>70
    return 'P','F'
    
grade([50,85,60,100])

Current output:

('P', 'F')
9
  • 2
    What about ==70? Commented Jun 20, 2023 at 6:07
  • 1
    I posted an answer but looping over the list would be a much simpler solution. Why no loopsies? :( Commented Jun 20, 2023 at 6:12
  • 3
    Just use a Comprehension: res = ['F' if x < 70 else 'P' for x in arr] Commented Jun 20, 2023 at 7:35
  • 1
    The grade function can just be: return np.where(input_array < 70, 'F', 'P') (Assuming that the result for exactly 70 should be P) Commented Jun 20, 2023 at 8:22
  • 1
    Looping always occurs anyway if only behind the scenes at some lower level of code.. How else can processes repeat? In a Comprehension the looping is in lower-level code which uses a C call. The comprehension I suggested is several times faster than the Numpy .where approach as also suggested. Commented Jun 20, 2023 at 9:48

1 Answer 1

1

You can use numpy for this task.

import numpy as np

arr1 = np.array([20, 80, 30, 100])
arr2 = np.array([50, 60, 90, 45])

mask1 = arr1 > 70
mask2 = arr2 > 70

output1 = np.where(mask1, 'P', 'F')
output2 = np.where(mask2, 'P', 'F')

print(output1)  # ['F' 'P' 'F' 'P']
print(output2)  # ['F' 'F' 'P' 'F']
Sign up to request clarification or add additional context in comments.

2 Comments

how about using def function but without looping ?
@AmeliaPutriDamayanti Your function wouldn't work. It doesn't do anything besides return a tuple of ('P', 'F').

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.