Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print Numpy arrays without any extra notation (square brackets [ ] and spaces between elements)?

I have a 2-dimensional numpy array that looks like this:

[[a b c]
 [d e f]
 [g h i]]

I'd like to print it without any of the default notational fluff that typically comes with arrays; namely the [, ] and the spaces between the elements. Something like this:

abc
def
ghi

Is it possible to do such a thing (without a trivial and possibly expensive Python loop, of course)?

I have looked at numpy.set_printoptions but it looks like it only sets presentational options for how elements are displayed, not the characters in between.

Edit: The elements in the array have a string representation that can be anything, including [, ] and whitespace. Minimal example of how to build such an array:

class custom(object):
    def __repr__(self):
        return 'a'
a = numpy.empty((5, 5), custom)
a.fill(custom())
print a
like image 822
Etienne Perot Avatar asked Mar 22 '12 19:03

Etienne Perot


2 Answers

While this pretty much amounts to a loop, I think this is probably the best you're going to get. Generally the join string method is pretty fast.

>>> a = np.array([[1,2,3],[2,4,6],[-1,-2,-3]])
>>> print '\n'.join(''.join(str(cell) for cell in row) for row in a)
123
246
-1-2-3

I think at this point you'd probably be best off implementing something and measuring how long it takes. My guess is that the slowest part of the code will be actually printing to console, not joining the strings together.

like image 90
Wilduck Avatar answered Sep 28 '22 03:09

Wilduck


np.savetxt(sys.stdout.buffer, a, fmt='%s', delimiter='')
like image 20
panda-34 Avatar answered Sep 28 '22 04:09

panda-34