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')
jared
  • 4,165
  • 1
  • 8
  • 31
  • 2
    What about `==70`? – mozway Jun 20 '23 at 06:07
  • 1
    I posted an answer but looping over the list would be a much simpler solution. Why no loopsies? :( – doneforaiur Jun 20 '23 at 06:12
  • 3
    Just use a Comprehension: `res = ['F' if x < 70 else 'P' for x in arr]` – user19077881 Jun 20 '23 at 07: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) – slothrop Jun 20 '23 at 08:22
  • @slothrop its showing error : TypeError: '<' not supported between instances of 'list' and 'int' . i tried that many times – Amelia Putri Damayanti Jun 20 '23 at 09:17
  • @user19077881 , it works but with looping :( – Amelia Putri Damayanti Jun 20 '23 at 09:19
  • What is `input_array`? Is it a numpy array, or a plain Python list? – slothrop Jun 20 '23 at 09:19
  • For example, if you make a 2D array, like `input_array = np.array([20,80,30,100],[50,60,90,45])` then that function will work fine. If `input_array` is a list of arrays or list of lists, then you can convert it to a 2D array inside the function, like: [Try it online!](https://tio.run/##VY5BD4IwDIXP7Ff0BksaU0VEjV49eyeELGHIEhlLGTH8@jn0xKV9ed/rS93i@9HmIZjBjezBzoNbQE1gnRCt7uDFqtWZsW72jWJWi7yKJAq4x8ju52yoSFj7me1KP71mna3hG5SEkD7SOJ6pFOJtJt@MXbPuKXZV1YHwTJgT7olqrArCE@GF8FjUtXBsrM/@v2xOpQzhCw "Python 3 – Try It Online") – slothrop Jun 20 '23 at 09:23
  • 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. – user19077881 Jun 20 '23 at 09:48
  • @slothrop superb, thanks a lot ! – Amelia Putri Damayanti Jun 20 '23 at 09:50
  • @user19077881 yes, much thanks ! – Amelia Putri Damayanti Jun 20 '23 at 09:50

1 Answers1

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']
doneforaiur
  • 1,308
  • 7
  • 14
  • 21