Suppose I have the following array.
假设我有以下数组。
l = np.asarray([1,3,5,7])
Out[552]: array([1, 3, 5, 7])
I can select the row twice using a index array np.asarray([[0,1],[1,2]])
:
我可以使用索引数组np.asarray([[0,1],[1,2]])选择行两次:
l[np.asarray([[0,1],[1,2]])]
Out[553]:
array([[1, 3],
[3, 5]])
It doesn't work if the index array have different length on each row:
如果索引数组在每行上具有不同的长度,则它不起作用:
l[np.asarray([[1,3],[1,2,3]])]
Traceback (most recent call last):
File "<ipython-input-555-3ec2ab141cd4>", line 1, in <module>
l[np.asarray([[1,3],[1,2,3]])]
IndexError: arrays used as indices must be of integer (or boolean) type
My desired output for this example would be:
我希望这个例子的输出是:
array([[3, 7],
[3, 5, 7]])
Can someone please help?
有人可以帮忙吗?
2 个解决方案
#1
1
I think this is the closest I can get.
我认为这是我能得到的最接近的。
import numpy as np
l = np.asarray([1, 3, 5, 7])
idx = [[1,3],[1,2,3]]
output = np.array([np.array(l[i]) for i in idx])
print output
Result:
[array([3, 7]) array([3, 5, 7])]
#2
0
You can get the result you are after if you build the lists seperately.
如果单独构建列表,则可以获得所需的结果。
Code:
l = np.asarray([1, 3, 5, 7])
# Build a sample array
print(np.array([[3, 7], [3, 5, 7]]))
# do the lookups into the original array
print(np.array([list(l[[1, 3]]), list(l[[1, 2, 3]])]))
Results:
[[3, 7] [3, 5, 7]]
[[3, 7] [3, 5, 7]]
#1
1
I think this is the closest I can get.
我认为这是我能得到的最接近的。
import numpy as np
l = np.asarray([1, 3, 5, 7])
idx = [[1,3],[1,2,3]]
output = np.array([np.array(l[i]) for i in idx])
print output
Result:
[array([3, 7]) array([3, 5, 7])]
#2
0
You can get the result you are after if you build the lists seperately.
如果单独构建列表,则可以获得所需的结果。
Code:
l = np.asarray([1, 3, 5, 7])
# Build a sample array
print(np.array([[3, 7], [3, 5, 7]]))
# do the lookups into the original array
print(np.array([list(l[[1, 3]]), list(l[[1, 2, 3]])]))
Results:
[[3, 7] [3, 5, 7]]
[[3, 7] [3, 5, 7]]