简体   繁体   English

垂直打印 numpy 数组的一维切片

[英]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.我正在尝试打印 numpy 数组的垂直切片,以便它垂直显示但始终水平打印。 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() :你也可以使用np.vstack()

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

Just an alternative, I sometimes use atleast_2d : 另一个选择是,我有时使用atleast_2d

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

(there are also atleast_1d , atleast_3d options too) (也有atleast_1datleast_3d选项)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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