遍历numpy矩阵行 [英] Iterate over a numpy Matrix rows

查看:1492
本文介绍了遍历numpy矩阵行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我试图在Google和网站中找到我的问题的答案(我认为这是非常基本的),但没有任何反应.

First, I tried to find an answer to my question ( which I think is pretty basic) searching in google and in the site, but nothing came up.

我正在尝试从一个numpy矩阵中获取行,但是我不能.例如,如果我使用这个:

I'm trying to get the rows from a numpy matrix, but I can't. For example if I use this:

result = numpy.matrix([[11, 12, 13],
                       [21, 22, 23],
                       [31, 32, 33]])

for p in result:
    print(p[0])

打印此:

[[11 12 13]]
[[21 22 23]]
[[31 32 33]]

如果我只使用p

我要做什么才能访问每一行? numpy.nditer(result)打印一个数组,我需要每一行来执行一些操作.

What I have to do to access every row? numpy.nditer(result) prints an array, and I need every row to perform some operations.

推荐答案

问题是您正在使用np.matrix.使用np.array代替,而无需索引即可简单地进行迭代:

The problem is you are using np.matrix. Use np.array instead and simply iterate without indexing:

result = np.array([[11, 12, 13],
                   [21, 22, 23],
                   [31, 32, 33]])

for p in result:
    print(p)

[11 12 13]
[21 22 23]
[31 32 33]

说明

您看到的是numpy.matrix要求每个具有2维的效果.对于NumPy而言,这是不必要的且是反模式.

What you are seeing is the effect of numpy.matrix requiring each row to have 2 dimensions. This is unnecessary and anti-pattern for NumPy.

numpy.matrix背后有一段历史.最初使用它是为了方便矩阵乘法运算符.但这不再是问题,因为可以使用@(Python 3.5+)而不是嵌套的dot调用.因此,默认情况下,使用numpy.array.

There is a history behind numpy.matrix. It was used initial for convenience of matrix multiplication operators. But this is no longer an issue since @ is possible (Python 3.5+) instead of nested dot calls. Therefore, by default, use numpy.array.

这篇关于遍历numpy矩阵行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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