Why doesn't the numpy matrix allow me to print lines?

Well, this is probably a very stupid question, but it really starts to hurt. I have a numpy matrix, and basically I print it in a row line by line. However, I want each line to 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]])

Suppose I want to print the first line and add '|' 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 is he doing this?

+3
source share
3 answers

arris returned as a type matrixthat cannot be an iterable object that plays perfectly with join.

arr list tolist(), 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'

, numpy.asarry, .

>>> 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.
+3

numpy ( [[ ]] ). .A.

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

, :

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

So arr [0,] is not a list or 1-d array, as you expected. On the other hand, your method works for an 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 say why this is happening. Another observation:

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

Source: https://habr.com/ru/post/1738836/


All Articles