[英]Using the logical indexing for 2D list in Python
我想在2D列表中使用逻辑索引,但似乎不支持此功能。
# For example
twoDimList = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
for rowIdx in range(0, len(twoDimList)):
for colIdx in range(0, len(twoDimList[rowIdx])):
if twoDimList[rowIdx][colIdx] == 0:
twoDimList[rowIdx][colIdx] = np.nan
twoDimList[twoDimList == 0] = numpy.nan # In fact, it's illegal.
如何使这种设计模式更加巧妙。
根据您的评论, 列表不是一个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
dtype
在这里是至关重要的:如果你没有指定它,numpy会假设你已经给它一个整数矩阵,并且整数没有NaN(仅用于定义NaN的浮点数)。
您还可以为numpy数组提供另一个变量名称(但是在numpy数组中完成的更改将不会反映在原始Python列表中)。
如果您的原始列表是(基于您的样本数据):
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.]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.