.shape []在"for i in range(Y.shape [0])"中做了什么?

Hip*_*ein 58 python numpy matplotlib scipy

我试图逐行分解一个程序.Y是一个数据矩阵,但我找不到任何.shape[0]确切的具体数据.

for i in range(Y.shape[0]):
    if Y[i] == -1:
Run Code Online (Sandbox Code Playgroud)

该程序使用numpy,scipy,matplotlib.pyplot和cvxopt.

unu*_*tbu 100

shapenumpy数组的属性返回数组的维度.如果Yn行和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
Run Code Online (Sandbox Code Playgroud)


Viv*_*han 32

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
Run Code Online (Sandbox Code Playgroud)

给出行数

c.shape[1] 
4
Run Code Online (Sandbox Code Playgroud)

给出列数


Lev*_*von 10

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)
Run Code Online (Sandbox Code Playgroud)

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

  • @HipsterCarlGoldstein只是一个友好的说明,如果提供的这些答案中的任何一个解决了您的问题,请考虑[通过单击答案旁边的复选标记接受它](http://meta.stackexchange.com/questions/5234/how-does-接受-的回答工作/ 5235#5235).这将为您和回答者提供一些代表点,并将此问题标记为已解决 - 谢谢. (2认同)

Dro*_*ool 5

在 python 中,假设你已经加载了一些变量序列中的数据:

train = pandas.read_csv('file_name')
>>> train
train([[ 1.,  2.,  3.],
        [ 5.,  1.,  2.]],)
Run Code Online (Sandbox Code Playgroud)

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

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