python .shape[]在“for i in range(Y.shape[0])"中有什么作用?

slmsl1lt  于 2022-12-28  发布在  Python
关注(0)|答案(6)|浏览(307)

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

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

这个程序使用了numpy、scipy、matplotlib、pyplot和cvxopt。

6yjfywim

6yjfywim1#

numpy数组的shape属性返回数组的维数。如果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
dly7yett

dly7yett2#

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

提供列数

2izufjch

2izufjch3#

shape是一个元组,它指示数组的维数,所以在您的示例中,由于Y.shape[0]的索引值为0,因此您将沿着数组的第一维进行操作。
从链接

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有更多的例子。

zbdgwd5y

zbdgwd5y4#

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

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

我想检查“file_name”的维度是什么。我已将文件存储在train中

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

p5fdfcr15#

在Python中,shape()在Pandas中用于给予行数/列数:
行数由下式给出:

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

列数由下式给出

train.shape[1]
jum4pzuy

jum4pzuy6#

shape()由具有两个参数行和列的数组组成。
如果你搜索shape[0],那么它会给你行数。shape[1]会给你列数。

相关问题