Home > Enterprise >  How to split with comma in numpy.ndarray without using for and while
How to split with comma in numpy.ndarray without using for and while

Time:02-13

I made a grade function that changes the values to P (Pass) and F (Fail), with the code as below:

def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    print(*grade_index_row,sep=', ')
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

Output : ['P' 'F' 'P' 'F' 'P'], ['P' 'P' 'P' 'P' 'F'], ['P' 'P' 'F' 'F' 'P']

How if I wanna put a comma on each array contents to be like this [[P,F,P], [P,P,P], [F,P,F], [F,F,P]]

CodePudding user response:

Here's one way:

def grade(input_array):
    grade_index_rows = np.where(input_array>= 70, "P", "F")
    print(*[f"[{','.join(row)}]" for row in grade_index_rows], sep=', ')
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

Result:

[P,F,P,F,P], [P,P,P,P,F], [P,P,F,F,P]

What you're getting from your example appears to be due to how Numpy chooses to represent a numpy.ndarray as a string. I've never noticed that it produces that kinda strange formatting. This new version of the code takes over the formatting of these arrays so that they can be formatted however you want.

CodePudding user response:

You should use np.array2string with a seperator in print.

-This below implementation will return output in string type.

def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    val = np.array2string(grade_index_row, separator=', ')
    print(type(val))
    print(val)
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

output:

<class 'str'>

[['P', 'F', 'P', 'F', 'P'], ['P', 'P', 'P', 'P', 'F'], ['P', 'P', 'F', 'F', 'P']]

-If you want result in List format then use this:

def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    val = np.array2string(grade_index_row, separator=', ')
    val = eval(val)
    print(type(val))
    print(val)
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

Output:

<class 'list'>

[['P', 'F', 'P', 'F', 'P'], ['P', 'P', 'P', 'P', 'F'],['P', 'P', 'F', 'F', 'P']]

  • Related