操作 2D numpy 数组时遇到问题(如下)。如果满足给定条件,我正在使用 np.where 添加值,但似乎不起作用。这是根本不可能的还是我犯了一个简单的错误?
a = ['circle','square']
b=['north','south']
c=['red','blue']
d=['long','short']
x = []
for shape in a:
for direction in b:
for color in c:
for length in d:
x.append([shape, direction, color, length, 0])
x = np.array(x)
# conditional add - if condition is met, add 1 to numeric index, else assign value of 2
x[:,4] = np.where((x[:,0]=='circle') & (x[:,1]=='south'), x[:,4]+1, 2)
一个解决方案是在创建 numpy 数组时使用索引而不是标签;这样它将是一个数字数组,并且您的最后一条语句将起作用:
from itertools import product
import numpy as np
parameters = [
['circle', 'square'],
['north', 'south'],
['red', 'blue'],
['long', 'short'],
]
x = np.array(list(product(*map(lambda my_list: range(len(my_list)), parameters), [0])))
x[:,4] = np.where((x[:,0]==0) & (x[:,1]==1), x[:,4]+1, 2)