.shape[] 在“for i in range(Y.shape[0])”中做了啥?

Posted

技术标签:

【中文标题】.shape[] 在“for i in range(Y.shape[0])”中做了啥?【英文标题】:What does .shape[] do in "for i in range(Y.shape[0])"?.shape[] 在“for i in range(Y.shape[0])”中做了什么? 【发布时间】:2012-04-29 07:49:35 【问题描述】:

我正在尝试逐行分解程序。 Y 是一个数据矩阵,但我找不到任何关于 .shape[0] 究竟做了什么的具体数据。

for i in range(Y.shape[0]):
    if Y[i] == -1:

此程序使用 numpy、scipy、matplotlib.pyplot 和 cvxopt。

【问题讨论】:

docs.scipy.org/doc/numpy/reference/generated/… 或 docs.scipy.org/doc/numpy/reference/generated/… 【参考方案1】:

numpy 数组的shape 属性返回数组的维度。如果Y 具有n 行和m 列,则Y.shape(n,m)。所以Y.shape[0]n

In [46]: Y = np.arange(12).reshape(3,4)

In [47]: Y
Out[47]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [48]: Y.shape
Out[48]: (3, 4)

In [49]: Y.shape[0]
Out[49]: 3

【讨论】:

【参考方案2】:

shape 是一个元组,可以指示数组中的维数。因此,在您的情况下,由于 Y.shape[0] 的索引值为 0,因此您正在沿着数组的第一个维度工作。

从 http://www.scipy.org/Tentative_NumPy_Tutorial#head-62ef2d3c0a5b4b7d6fdc48e4a60fe48b1ffe5006

 An array has a shape given by the number of elements along each axis:
 >>> a = floor(10*random.random((3,4)))

 >>> a
 array([[ 7.,  5.,  9.,  3.],
        [ 7.,  2.,  7.,  8.],
        [ 6.,  8.,  3.,  2.]])

 >>> a.shape
 (3, 4)

http://www.scipy.org/Numpy_Example_List#shape 还有更多 例子。

【讨论】:

@HipsterCarlGoldstein 友情提示,如果提供的这些答案中的任何一个解决了您的问题,请考虑accepting it by clicking the checkmark next to the answer。这将为您和回答者提供一些代表点,并将此问题标记为已解决 - 谢谢。【参考方案3】:

shape 是一个给出数组维度的元组..

>>> c = arange(20).reshape(5,4)
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

c.shape[0] 
5

给出行数

c.shape[1] 
4

给出列数

【讨论】:

【参考方案4】:

在 Python 中,shape() 在 pandas 中用于给出行数/列数:

行数由下式给出:

train = pd.read_csv('fine_name') //load the data
train.shape[0]

列数由

给出
train.shape[1]

【讨论】:

【参考方案5】:

在 python 中,假设你已经在某个变量 train 中加载了数据:

train = pandas.read_csv('file_name')
>>> train
train([[ 1.,  2.,  3.],
        [ 5.,  1.,  2.]],)

我想检查“文件名”的尺寸。我已将文件存储在火车中

>>>train.shape
(2,3)
>>>train.shape[0]              # will display number of rows
2
>>>train.shape[1]              # will display number of columns
3

【讨论】:

【参考方案6】:

shape() 由具有两个参数行和列的数组组成。

如果您搜索shape[0],那么它会为您提供行数。 shape[1] 会给你列数。

【讨论】:

以上是关于.shape[] 在“for i in range(Y.shape[0])”中做了啥?的主要内容,如果未能解决你的问题,请参考以下文章

python中的for i in range怎么用?

python中for i in range(0, 3.0 , 0.1)为啥错?

django模块不能用for i in range(0, 5)总报错

python中的for i in range怎么用

python中的for i in range怎么用

python for i in range(x)应用的问题