为什么我的数据没有被屏蔽?

data = [[0, 1, 1, 5, 5, 5, 0, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 6, 6, 6],

        [1, 1, 1, 0, 5, 5, 5, 0, 2, 2, 0, 0, 2, 0, 0, 6, 6, 6, 0, 0, 6, 6],

        [1, 1, 1, 0, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 6, 0, 0, 6, 6]]

我拥有的数据对象是 <class 'numpy.ndarray'>


知道数据是一个numpy对象,我做了以下工作:


data = np.array(data)

我想将输入中的列表中的数字设置为0,这是我尝试过的:


data[~np.isin(data,[2,4])] = 0

我期望在前一个矩阵中所有2和4出现都是0,其余的保持它们的值,我得到了什么:


TypeError:仅整数标量数组可以转换为标量索引


还尝试使用np.array给定错误将数据作为numpy数组给出。


烙印99
浏览 185回答 1
1回答

HUH函数

np.isin如果打算将那些匹配值设置为0,则不应忽略该掩码。下面的代码可以正常工作:另外,您应该使data一个numpy数组,而不是列表列表。In [10]: data = np.array([[0, 1, 1, 5, 5, 5, 0, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 6, 6, 6],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[1, 1, 1, 0, 5, 5, 5, 0, 2, 2, 0, 0, 2, 0, 0, 6, 6, 6, 0, 0, 6, 6],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[1, 1, 1, 0, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 6, 0, 0, 6, 6]])&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;In [11]: data[np.isin(data, [2, 4])] = 0In [12]: dataOut[12]:&nbsp;array([[0, 1, 1, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6],&nbsp; &nbsp; &nbsp; &nbsp;[1, 1, 1, 0, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 0, 0, 6, 6],&nbsp; &nbsp; &nbsp; &nbsp;[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 6, 6]])只是为了重现您的错误:In [13]: data = [[0, 1, 1, 5, 5, 5, 0, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 6, 6, 6],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[1, 1, 1, 0, 5, 5, 5, 0, 2, 2, 0, 0, 2, 0, 0, 6, 6, 6, 0, 0, 6, 6],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[1, 1, 1, 0, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 6, 0, 0, 6, 6]]&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;In [14]: data[np.isin(data, [2, 4])] = 0---------------------------------------------------------------------------TypeError&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Traceback (most recent call last)<ipython-input-14-06ee1662f1f2> in <module>()----> 1 data[np.isin(data, [2, 4])] = 0TypeError: only integer scalar arrays can be converted to a scalar index
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python