python 矩阵搜索

发布于 2024-12-25 19:43:22 字数 351 浏览 4 评论 0原文

如果我有以下矩阵:

import numpy

ar = numpy.array((('0','1','2','3'), ('1','a','b','b'), ('2','b','c','d')), str)
print(ar)

输出:

[['0' '1' '2' '3']
 ['1' 'a' 'b' 'b']
 ['2' 'b' 'c' 'd']]

并且我想获取满足行和列条件的值。标题行是列(可以是字符串),左侧第一列是所有行(可以是字符串)。因此,如果我的列为“2”,行为“2”,我会得到“c”。我不知道“c”,只知道行和列的值。我该怎么做呢?

If I have the following matrix:

import numpy

ar = numpy.array((('0','1','2','3'), ('1','a','b','b'), ('2','b','c','d')), str)
print(ar)

Output:

[['0' '1' '2' '3']
 ['1' 'a' 'b' 'b']
 ['2' 'b' 'c' 'd']]

And I want to get the value where the condition for row and column is met. The header row are the columns (could be strings) and the first column on the left are all rows (could be strings). So if I have '2' for column and '2' for row I would get 'c'. I don't know 'c' yet only the values for rows and columns. How would I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泪意 2025-01-01 19:43:22

您可以使用 numpy.where :

In [7]: numpy.where(ar == 'c')
Out[7]: (array([2]), array([2]))

并且:

In [8]: ar[numpy.where(ar == 'c')]
Out[8]: 
array(['c'], 
      dtype='|S1')

You can use numpy.where:

In [7]: numpy.where(ar == 'c')
Out[7]: (array([2]), array([2]))

and:

In [8]: ar[numpy.where(ar == 'c')]
Out[8]: 
array(['c'], 
      dtype='|S1')
叶落知秋 2025-01-01 19:43:22

如果您的意思是搜索“c”:

numpy.where(ar == 'c')

If you mean searching for 'c':

numpy.where(ar == 'c')
绝對不後悔。 2025-01-01 19:43:22
ar = [['0', '1', '2', '3'],
 ['1', 'a', 'b', 'b'],
 ['2', 'b', 'c', 'd']]

print(ar[2][2])

以上仅用于访问第 2 列第 2 行中的“c”,如果您想访问整个列,则必须:

for i in range(0, 3):
    print(ar[2][i])
ar = [['0', '1', '2', '3'],
 ['1', 'a', 'b', 'b'],
 ['2', 'b', 'c', 'd']]

print(ar[2][2])

The above is just for accessing the 'c' in column 2, row 2, if you want to access a whole column you would have to:

for i in range(0, 3):
    print(ar[2][i])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文