0

我正在尝试以列表形式提取一列 numpy 矩阵。我已经使用了方法tolist(),但它对我的目的没有用。让我们看看代码。

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!')

输出

[1, 2, 4, 6]
[[1], [3]]

如您所见,方法返回的列表tolist()在 if 语句中被忽略。现在,如果我不能更改 if 语句(出于任何原因),我该如何管理b它,就好像它是一个列表一样a

4

1 回答 1

1

问题是numpy.matrix对象总是保持二维。转换为数组,然后展平:

>>> col = b[:,0].getA().flatten().tolist()
>>> col
[1, 3]

或者也许只是与正常numpy.ndarray的工作...

>>> a = b.getA()
>>> a[:,0]
array([1, 3])

对...

>>> b[:,0]
matrix([[1],
        [3]])
于 2017-03-27T23:02:31.517 回答