我有以下2x2的字典数组:
a = np.array([[{'x_id':0, 'y_id':0},{'x_id':1, 'y_id':1}],[{'x_id':2, 'y_id':0},{'x_id':3, 'y_id':1}]])
我想获得一个2x2的数字数组,对应于键'x_id'
,[[0, 1], [2, 3]]
的值,即:
0 1
2 3
除了double for循环之外,还有其他方法吗?那就是:
numbers = [[a[i,j]['x_id'] for j in range(2)] for i in range(2)]
答案 0 :(得分:2)
如果您在代码中谈论 explicit for循环,则可以flatten
数组并使用单个for循环完成工作,然后重塑最终数组
numbers = np.array([i['x_id'] for i in a.flatten()]).reshape(a.shape)
# array([[0, 1],
# [2, 3]])
另一种解决方案是在平坦数组上使用itemgetter
,
import operator
numbers = np.array(list(map(operator.itemgetter('x_id'), a.flatten()))).reshape(a.shape)
性能:两种方法花费的时间相似
%timeit np.array([i['x_id'] for i in a.flatten()]).reshape(a.shape)
# 4.16 µs ± 676 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.array(list(map(operator.itemgetter('x_id'), a.flatten()))).reshape(a.shape)
# 4.9 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)