Numpy 将 1d 数组重塑为 1 列的 2d 数组 [英] Numpy reshape 1d to 2d array with 1 column

查看:67
本文介绍了Numpy 将 1d 数组重塑为 1 列的 2d 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy 中,结果数组的维度在运行时会有所不同.一维数组和具有 1 列的二维数组之间经常存在混淆.在一种情况下我可以遍历列,在另一种情况下我不能.

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?

推荐答案

You can do -

You could do -

ar.reshape(ar.shape[0],-1)

reshape 的第二个输入:-1 处理第二个轴的元素数量.因此,对于 2D 输入案例,它不会改变.对于 1D 输入情况,它创建一个 2D 数组,由于 ar.shape[0],这是元素的总数.

That second input to reshape : -1 takes care of the number of elements for the second axis. Thus, for a 2D input case, it does no change. For a 1D input case, it creates a 2D array with all elements being "pushed" to the first axis because of ar.shape[0], which was the total number of elements.

样品运行

一维案例:

In [87]: ar
Out[87]: array([ 0.80203158,  0.25762844,  0.67039516,  0.31021513,  0.80701097])

In [88]: ar.reshape(ar.shape[0],-1)
Out[88]: 
array([[ 0.80203158],
       [ 0.25762844],
       [ 0.67039516],
       [ 0.31021513],
       [ 0.80701097]])

二维案例:

In [82]: ar
Out[82]: 
array([[ 0.37684126,  0.16973899,  0.82157815,  0.38958523],
       [ 0.39728524,  0.03952238,  0.04153052,  0.82009233],
       [ 0.38748174,  0.51377738,  0.40365096,  0.74823535]])

In [83]: ar.reshape(ar.shape[0],-1)
Out[83]: 
array([[ 0.37684126,  0.16973899,  0.82157815,  0.38958523],
       [ 0.39728524,  0.03952238,  0.04153052,  0.82009233],
       [ 0.38748174,  0.51377738,  0.40365096,  0.74823535]])

这篇关于Numpy 将 1d 数组重塑为 1 列的 2d 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆