带有1列的Numpy重塑1d至2d数组
问题描述:
在numpy
中,结果数组的尺寸在运行时会有所不同.
一维数组和具有一列的二维数组之间经常会混淆.
在一种情况下,我可以遍历列,而在另一种情况下,我不能.
In numpy
the dimensions of the resulting array vary at run time.
There is often confusion between a 1d array and a 2d array with 1 column.
In one case I can iterate over the columns, in the other case I cannot.
您如何优雅地解决该问题?
为了避免使用if
语句检查维数而乱码,我使用以下函数:
How do you solve elegantly that problem?
To avoid littering my code with if
statements checking for the dimensionality, I use this function:
def reshape_to_vect(ar):
if len(ar.shape) == 1:
return ar.reshape(ar.shape[0],1)
return ar
但是,这感觉不雅且昂贵.有更好的解决方案吗?
However, this feels inelegant and costly. Is there a better solution?
答
最简单的方法:
ar.reshape(-1, 1)