带有1列的Numpy重塑1d至2d数组 [英] Numpy reshape 1d to 2d array with 1 column

查看:139
本文介绍了带有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)

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

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