1

Despite this seeming an easy task, I didn't find a satisfying way of doing it. There are several solutions based on map or try/except but none of these seems to me solid enough (e.g. working in a general case and with 2D arrays).

This can be done with pandas, but I would like to avoid importing an entire library just for this task, is it possible to do it just with numpy functions?

To make an example of what I mean, from an array like:

>>a=np.vstack([['zero','one'],np.array(np.arange(2)).T]).astype('|S') >>print a [['zero' 'one'] ['0' '1']] 

the desired output is:

zero one 0 1 

2 Answers 2

3

You can use a list comprehension within str.join():

>>> print '\n'.join([' '.join(i) for i in a]) zero one 0 1 
Sign up to request clarification or add additional context in comments.

5 Comments

You can drop the square brackets or use map(' '.join, a) for the inner part.
@AlexHall No, since the join method needs to preallocate the size of string it needs to generate the items once before concatenating, since list comparison is faster than generator expression within str.join() function.
I'm assuming that string formatting like this doesn't need to be micro-optimised.
@AlexHall Yes, but don't forget that sparks can cause huge fireworks :-)
I like this solution, straightforward, but for some reason I missed it. And I like it is a one liiner. Thanks
0

Not sure if this is what you are asking for but a function using regular python can be made to print out the 2d array like you depicted:

def format_array(arr): for row in arr: for element in row: print(element, end=" ") print('') return arr 

This prints:
zero one
0 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.