为什么一维数组的形状未将行数显示为1? [英] Why does the shape of a 1D array not show the number of rows as 1?

查看:40
本文介绍了为什么一维数组的形状未将行数显示为1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道numpy数组有一个叫做shape的方法,该方法返回[行数,列数],shape [0]给出行数,shape [1]给出列数.

I know that numpy array has a method called shape that returns [No.of rows, No.of columns], and shape[0] gives you the number of rows, shape[1] gives you the number of columns.

a = numpy.array([[1,2,3,4], [2,3,4,5]])
a.shape
>> [2,4]
a.shape[0]
>> 2
a.shape[1]
>> 4

但是,如果我的数组只有一行,那么它将返回[列数].并且shape [1]将不在索引中.例如

However, if my array only have one row, then it returns [No.of columns, ]. And shape[1] will be out of the index. For example

a = numpy.array([1,2,3,4])
a.shape
>> [4,]
a.shape[0]
>> 4    //this is the number of column
a.shape[1]
>> Error out of index

现在,如果该数组可能只有一行,如何获取numpy数组的行数?

Now how do I get the number of rows of an numpy array if the array may have only one row?

谢谢

推荐答案

当您拥有2D数组时,的概念适用.但是,数组numpy.array([1,2,3,4])是一维数组,因此只有一个维度,因此shape正确地返回一个可迭代的单值.

The concept of rows and columns applies when you have a 2D array. However, the array numpy.array([1,2,3,4]) is a 1D array and so has only one dimension, therefore shape rightly returns a single valued iterable.

对于同一阵列的2D版本,请考虑以下内容:

For a 2D version of the same array, consider the following instead:

>>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces
>>> a.shape
(1, 4)

这篇关于为什么一维数组的形状未将行数显示为1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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