How to Convert NumPy Array to String and Include Commas

Question:

I have a NumPy array called ‘colors’. Colors has a shape of (N, 3). I’m trying to convert colors into a string and format it so that each item in axis = 0 is seperated by a comma.

EX. (1,2,3), (4,5,6), (7,8,9), ...

I know about the array2string function, but I’m struggling to include commas after converting the array to a string.

Answers:

You could convert each row to a tuple and then join the string representations of each tuple with a ,:

a = np.array(((1,2,3), (4,5,6), (7,8,9), (10, 11, 12)))
s = ', '.join(str(tuple(r)) for r in a)
print(s)

Output:

(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)
Answered By: Nick