I'm trying to extract a column of a numpy matrix in a list form. I've used the method tolist()
, but it is not useful for my purpose.
Let see the code.
import numpy as np
def get_values(feature):
'''
This method creates a lst of all values in a feature, without repetitions
:param feature: the feature of which we want to extract values
:return: lst of the values
'''
values = []
for i in feature:
if i not in values:
values.append(i)
return values
lst=[1, 2, 4, 4, 6]
a=get_values(lst)
print(a)
b=np.matrix('1 2; 3 4')
col = b[:,0].tolist()
print(col)
if col == [1, 3]:
print('done!')
OUTPUT
[1, 2, 4, 6]
[[1], [3]]
As you can see, the returned list from method tolist()
is ignored in the if statement. Now, if I can't change the if statement (for any reason) how can I do to manage the b
as if it were a list like a
?
The problem is that numpy.matrix
objects always maintain two dimensions. Convert to array, then flatten:
>>> col = b[:,0].getA().flatten().tolist()
>>> col
[1, 3]
Or maybe just work with normal numpy.ndarray
s...
>>> a = b.getA()
>>> a[:,0]
array([1, 3])
vs...
>>> b[:,0]
matrix([[1],
[3]])