简体   繁体   English

无法访问 Python 二维数组中的行元素?

[英]Can't access row elements in Python 2d array?

I have created a 2d matrix using Scipy's coo_matrix, and have a matrix M as such:我使用 Scipy 的 coo_matrix 创建了一个二维矩阵,并有一个矩阵 M 如下:

df = pd.DataFrame(columns=["hub", "auth", "weight"])
M = coo_matrix((df.iloc[:,2], (df.iloc[:,0],df.iloc[:,1])), shape=(len(hubs) + len(auths), len(hubs) + len(auths)))
M = M.todense()

[[0 0 0 1 1 1 0]
[0 0 0 1 1 0 0]
[0 0 0 0 0 0 1]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]]

I can successfully slice the array to get its columns and the elements in each column:我可以成功地对数组进行切片以获取其列和每列中的元素:

col = M[:,3]
val = col[0]

where val is equal to 1. I try to do something similar to extract a row:其中 val 等于 1。我尝试做类似的事情来提取一行:

row = M[0]
val = row[2]

which should also return 1, but instead val returns这也应该返回 1,但 val 返回

[[0 0 0 1 1 1 0]]

What am I doing wrong here?我在这里做错了什么?

Since it is a numpy array (as DYZ pointed it that .todense() is called on the original coo_matrix):由于它是一个 numpy 数组(正如 DYZ 指出的那样,在原始 coo_matrix 上调用了.todense() ):

Notice that your original matrix, or 2d array is 7 x 7 (7 rows by 7 columns).请注意,您的原始矩阵或二维数组为 7 x 7(7 行 x 7 列)。 When you call col = M[:,3] , you are saying you want the 3rd column and all rows, which is a resulting 7 x 1 matrix (7 rows by 1 column).当您调用col = M[:,3] ,您是说您想要第 3 列和所有行,这是一个 7 x 1 矩阵(7 行 x 1 列)。 When you call col[2] , you are actually calling col[2,:] or getting the 2nd row (which is now just a 1 x 1 matrix).当您调用col[2] ,您实际上是在调用col[2,:]或获取第二行(现在只是一个 1 x 1 矩阵)。

Now, if you call row = M[0] , you are actually calling row = M[0,:] or getting the 0th row and all columns, which is a 1 x 7 matrix (1 column by 7 rows).现在,如果您调用row = M[0] ,您实际上是在调用row = M[0,:]或获取第 0 行和所有列,这是一个 1 x 7 矩阵(1 列乘 7 行)。 Thus calling val = row[2] gives an indexerror as you only have 1 row in your new matrix.因此,调用val = row[2]会产生索引错误,因为您的新矩阵中只有 1 行。 You could instead call val = row[:,2] to get the 2nd column.您可以改为调用val = row[:,2]来获取第二列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM