开发者

Why won't numpy matrix let me print its rows?

Okay this is probably a really dumb question, however it's really starting to hurt. I have a numpy matrix, and basically I print it out row by row. However I want to make each row be formatted and separated properly.

>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> arr
matrix([[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]])

Lets say i want to print the first row, and add a '|' between each element:

>>> '|'.join(map(str, arr[0,]))
'[[0 1 2 3 4]]'

Err...

>>> '|'.join(map(lambda x: str(x[0]),开发者_运维技巧 arr[0]))
'[[0 1 2 3 4]]'

I am really confused by this behavior why does it do this?


arr is returned as a matrix type, which may not be an iterable object that plays nicely with join.

You could convert arr to a list with tolist() and then perform your join.

>>> a = arr.tolist() # now you can manipulate the list.
>>> for i in a:
 '|'.join(map(str,i))    

'0|1|2|3|4'
'0|1|2|3|4'
'0|1|2|3|4'
'0|1|2|3|4'
'0|1|2|3|4'

Or with an array using numpy.asarry for that matter

>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> ele = numpy.asarray(arr)
>>> '|'.join(map(str,ele[0,]))
'0|1|2|3|4' # as per your example.


In numpy, slices of matrices are matrices (note the double braces [[ ]] in your example). An easy way around this is to get the array representation using the .A attribute.

'|'.join(map(str, arr.A[0,]))

produces what you want:

0|1|2|3|4


>>> arr[0,]
matrix([[0, 1, 2, 3, 4]])
>>> len(arr[0,])
1

So arr[0,] is not a list or an 1-d array as you expected. On the other hand, your method works for the example matrix from the numpy tutorial:

>>> def f(x,y):
...         return 10*x+y
...
>>> b = fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])
>>> len(b[0,])
4
>>> '|'.join(map(str, b[0,]))
'0|1|2|3'

I am not familiar with numpy, so I can tell why this happens. One more observation:

>>> type(arr)
<class 'numpy.matrixlib.defmatrix.matrix'>
>>> type(b)
<type 'numpy.ndarray'>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜