0

I have an ndarray of centroids (k means algorithm) and I want to create a to string for it that turns the ndarray into a string of specific format (shown below) is there an elegant way to do it?

I've tried to play a bit with python's join and split but couldn't quite get the result I wanted.

I wish to turn this:

[[0.7240662  0.64965678 0.55572689]
 [0.50786521 0.43429734 0.35474341]
 [0.04124227 0.03325809 0.04185308]
 [0.19986216 0.17889411 0.17727035]]

Into this:

"[0.72, 0.64, 0.55], [0.50, 0.43, 0.35], [0.04, 0.03, 0.04], [0.19,0.17,0.17]"

2 Answers 2

1

You can use np.array2string(...). There are some examples on the documentation page. It would look like this:

import numpy as np

x = np.random.random((3, 4))
x_str = np.array2string(x, precision=2, separator=', ').replace('\n', '')[1:-1]

print(x)
# [[0.05857399 0.44516104 0.33626309 0.45332413]
#  [0.37389644 0.50240347 0.11313364 0.10669512]
#  [0.38341254 0.52692079 0.1750295  0.44375732]]

print(x_str)
# [0.06, 0.45, 0.34, 0.45], [0.37, 0.5 , 0.11, 0.11], [0.38, 0.53, 0.18, 0.44]
Sign up to request clarification or add additional context in comments.

Comments

0

Ok let's go step by step. Let's call your array a.

>>> a
array([[0.7240662 , 0.64965678, 0.55572689],
       [0.50786521, 0.43429734, 0.35474341],
       [0.04124227, 0.03325809, 0.04185308],
       [0.19986216, 0.17889411, 0.17727035]])

str convert a into string.

>>> str(a)
'[[0.7240662  0.64965678 0.55572689]\n [0.50786521 0.43429734 0.35474341]\n [0.04124227 0.03325809 0.04185308]\n [0.19986216 0.17889411 0.17727035]]'

Then we remove the first and last bracket with a slice.

>>> str(a)[1:-1]
'[0.7240662  0.64965678 0.55572689]\n [0.50786521 0.43429734 0.35474341]\n [0.04124227 0.03325809 0.04185308]\n [0.19986216 0.17889411 0.17727035]'

Then we use replace to format it the way you want.

>>> str(a)[1:-1].replace('\n', ',')
'[0.7240662  0.64965678 0.55572689], [0.50786521 0.43429734 0.35474341], [0.04124227 0.03325809 0.04185308], [0.19986216 0.17889411 0.17727035]'

Comments

Your Answer

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.