在Python中使用2D列表的逻辑索引

在Python中使用2D列表的逻辑索引,python,numpy,Python,Numpy,我想在2D列表中使用逻辑索引,但它似乎不支持此功能 数据 原始来源 我的理想解决方案 如何使此设计模式更聪明。根据您的评论,列表不是numpy数组。您可以使用以下方法构造一个: import numpy as np # convert the 2d Python list into a numpy array twoDimList = np.array(twoDimList,dtype=np.float) twoDimList[twoDimList == 0] = np.nan 我们得到:

我想在2D列表中使用逻辑索引,但它似乎不支持此功能

数据 原始来源 我的理想解决方案
如何使此设计模式更聪明。

根据您的评论,列表不是numpy数组。您可以使用以下方法构造一个:

import numpy as np

# convert the 2d Python list into a numpy array
twoDimList = np.array(twoDimList,dtype=np.float)

twoDimList[twoDimList == 0] = np.nan
我们得到:

>>> twoDimList = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
>>> twoDimList = np.array(twoDimList,dtype=np.float)
>>> twoDimList[twoDimList == 0] = np.nan
>>> twoDimList
array([[ nan,  nan,  nan,   1.],
       [ nan,  nan,   1.,   1.],
       [ nan,   1.,   1.,   1.]])

twoDimList
是一个numpy数组吗?@WillemVanOnsem,亲爱的先生,像
twoDimList=[[0,0,0,1,1],[0,0,1,1],[0,1,1]。
亲爱的先生,谢谢你的回答。我现在成功了,但收到了错误消息<代码>值错误:无法将浮点NaN转换为整数。我将数组中的原始元素改为float正在工作。@Husky:这应该用
dtype
参数来解决。它工作正常,非常完美。感谢您的回答:]
twoDimList[twoDimList == 0] = numpy.nan # In fact, it's illegal.
import numpy as np

# convert the 2d Python list into a numpy array
twoDimList = np.array(twoDimList,dtype=np.float)

twoDimList[twoDimList == 0] = np.nan
twoDimList = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
>>> twoDimList = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
>>> twoDimList = np.array(twoDimList,dtype=np.float)
>>> twoDimList[twoDimList == 0] = np.nan
>>> twoDimList
array([[ nan,  nan,  nan,   1.],
       [ nan,  nan,   1.,   1.],
       [ nan,   1.,   1.,   1.]])