【问题标题】:How to interpret the result of `np.where`?如何解释 `np.where` 的结果?
【发布时间】:2019-11-09 15:12:31
【问题描述】:

我是一名刚接触 Numpy 的学生,并且没有扎实的基础。我目前正在尝试识别数组每一行中的最大整数,整数在数组中所在的行和列并将其打印出来。

但是,当尝试打印出最大整数元素的行和列时,我意识到输出会一直用“ (array..)”打印出元素的位置。无论如何我可以从我的输出中删除(array...) 吗?

import numpy as np

a = np.random.randint(1,1000,(3,4))

#MAX A(s)
maxa = a.max(axis = 1)
arra1 = maxa[np.asarray(0)]
arra2 = maxa[np.asarray(1)]
arra3 = maxa[np.asarray(2)]

#LOCATION OF MAX A(s)
arra1loc = np.where(a == arra1)

print('*** Contents of array a ***')
print(a)
print()

print('Max a = {}'.format(arra1))
print('Row and Column of {} is {}'.format(arra1,arra1loc))

我目前的输出:

*** Contents of array a ***
[[459 472 918  50]
 [562 556 145 843]
 [638 797 872  61]]

Max a = 918
Row and Column of 918 is (array([0]), array([2]))

我想要它是什么:

*** Contents of array a ***
[[459 472 918  50]
 [562 556 145 843]
 [638 797 872  61]]

Max a = 918
Row and Column of 918 is ([0], [2])

【问题讨论】:

  • print('Row and Column of {} is {}'.format(arra1,(arra1loc [0][0], arra1loc [1][0])))
  • 是的,我试过了。效果很好。谢谢!

标签: python arrays numpy


【解决方案1】:

您的array1loc 实际上是ndarraytuple,正如我们在此处看到的(array([0]), array([2])) 一样,您可以通过

print(type(arra1loc))    # <class 'tuple'>
print(type(arra1loc[0])) # <class 'numpy.ndarray'>

因此您需要将tolist() 应用于您的tuple 中的每个ndarray

# from numpy import ndarray
arra1loc = tuple(map(ndarray.tolist, arra1loc))
print('Row and Column of {} is {}'.format(arra1, arra1loc)) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 2017-05-02
    • 2017-04-25
    • 1970-01-01
    • 2018-06-14
    • 2021-08-12
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多