Home > Software engineering >  Getting Error while converting numpy.array into list and trying to find Index
Getting Error while converting numpy.array into list and trying to find Index

Time:06-23

This is my code,

l1=[[1,2,3],[4,5,6],[7,8,9]]

suppose, If I want to find the Index of an Item, I can easily find it like this

l1.index([7,8,9])
--output 
2

type(l1)
--output
list

But, When I try to convert the list into Numpy.array and then convert it back to list and then if I try to find the index of an element, I am getting an error

l1=list(np.array([[1,2,3],[4,5,6],[7,8,9]]))

l1.index([7,8,9])

enter image description here

Why am I getting this error and how to resolve this?

CodePudding user response:

You need to use tolist() function in order to get the proper conversion from np.array to Python built-in list:

import numpy as np

l1=[[1,2,3],[4,5,6],[7,8,9]]

print(l1.index([7,8,9]))

l1=np.array([[1,2,3],[4,5,6],[7,8,9]]).tolist()

print(l1.index([7,8,9]))

Output:

2
2

CodePudding user response:

In [4]: l1=[[1,2,3],[4,5,6],[7,8,9]]

In [5]: arr = np.array(l1)

In [6]: arr
Out[6]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

tolist performs a thorough conversion to python base structures - not just lists, but also the numeric elements.

In [7]: arr.tolist()
Out[7]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

list just converts the first dimension:

In [8]: list(arr)
Out[8]: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

It's equivalent to this list comprehension:

In [9]: [a for a in arr]
Out[9]: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

tolist is also faster.

As for your error

In [10]: list(arr).index([7,8,9])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 list(arr).index([7,8,9])

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

you have to understand how index works, and how == works for arrays.

index iterates through the elements of the list and applies an equality test, first with id and then with ==.

for the list of lists:

In [14]: [sublist==[7,8,9] for sublist in l1]
Out[14]: [False, False, True]

but for the list of arrays:

In [15]: [sublist==[7,8,9] for sublist in list(arr)]
Out[15]: 
[array([False, False, False]),
 array([False, False, False]),
 array([ True,  True,  True])]

For lists == tests the whole lists, and returns a simple True/False. For arrays, the result is an element-wise test, producing multiple True/False. That's what the "ambiguity" error is all about.

  • Related