I want to use logical indexing in the 2D list, but it seems not to support this feature.
# 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.
How can I make this design pattern more clever.
Based on your comment, the list is not a numpy array . You can construct one with:
import numpy as np
# convert the 2d Python list into a numpy array
twoDimList[twoDimList == 0] = np.nan
The dtype
is crucial here: if you do not specify it, numpy will assume you have given it a matrix of integers , and the integers do not have a NaN (only for floats a NaN is defined).
You can also give the numpy array another variable name (but the changes done in the numpy array will not reflect on the original Python list).
If your original list is (based on your sample data):
twoDimList = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
we get:
>>> 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.]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.