简体   繁体   中英

Print a 1-D slice of a numpy array vertically

I am trying to print a vertical slice of a numpy array so it displays vertically but it always prints horizontally. Given this square array:

a = np.ones([5,5])

I've tried:

print a[:,1]
print np.reshape(a[:,1], (1,-1))
print a[:,1].T
print [a[:,1].T]

which give me:

[ 1.  1.  1.  1.  1.]
[[ 1.  1.  1.  1.  1.]]
[ 1.  1.  1.  1.  1.]
[array([ 1.,  1.,  1.,  1.,  1.])]

I want to see:

[[1],
 [1],
 [1],
 [1], 
 [1]]

You need to add a new axis:

a[:, 1, None]
Out: 
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

or

a[:, 1, np.newaxis]
Out: 
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

I'd wrap the second indexer in brackets

a[:, [1]]

array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

Another way to add a dimension:

a[:,1:2]
Out:
array([[ 1.],
   [ 1.],
   [ 1.],
   [ 1.],
   [ 1.]])

You could also use np.vstack() :

print(np.vstack(a[:,1]))
[[1.]
 [1.]
 [1.]
 [1.]
 [1.]]

Just an alternative, I sometimes use atleast_2d :

np.atleast_2d(a[:, 1]).T

(there are also atleast_1d , atleast_3d options too)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM