简体   繁体   English

从 `2D` numpy 的每一行中删除 `n` 元素,其中 `n` 逐行变化

[英]Removing `n` elements from each row in `2D` numpy where `n` varies row by row

How would one remove n elements from 2D numpy array where n varies in each row?如何从每行中n变化的2D numpy 数组中删除n元素?

For example:例如:

# input array 
[[1,2,3],
 [3,1,2],
 [1,2,3],
 [4,5,2],
 [5,6,7]]

with

# n elements to remove from each row
[0, 2, 1, 2, 1]

would result in:会导致:

[[1,2,3],
 [3],
 [1, 2],
 [4],
 [5,6]]

Do note that the result does not need to be a numpy array(and won't be as Michael noticed in the comments), just an arbitrary Python list of lists.请注意,结果不需要是 numpy 数组(也不会像迈克尔在评论中注意到的那样),只是一个任意的 Python 列表列表。

Herewith I have come up with a solution.为此,我想出了一个解决方案。 Give it a try:试试看:

arr = [[1,2,3],
 [3,1,2],
 [1,2,3],
 [4,5,2],
 [5,6,7]]
new_arr =[]
lst = [0, 2, 1, 2, 1]
count=0
for i in arr:
    remove = lst[count]
    count = count+1
    temp = i[:len(i)-remove]
    new_arr.append(temp)
print(new_arr)   

  

As has been pointed out in the comments, the result wouldn't be a numpy array.正如评论中所指出的,结果不会是 numpy 数组。

Given the example data from your question:鉴于您的问题的示例数据:

>>> a = [[1,2,3],
...  [3,1,2],
...  [1,2,3],
...  [4,5,2],
...  [5,6,7]]
>>> remove_n_tail_list = [0, 2, 1, 2, 1]

You could for example use a list comprehension to get the desired result:例如,您可以使用列表推导来获得所需的结果:

>>> [row[:len(row) - remove_n_tail] for row, remove_n_tail in zip(a, remove_n_tail_list)]
[[1, 2, 3], [3], [1, 2], [4], [5, 6]]

In that solution, row[:len(row) - remove_n_tail] is selecting the values up to the length of the row ( len(row) ), minus the number of values you want to remove from the end ( remove_n_tail ).在该解决方案中, row[:len(row) - remove_n_tail]选择的值不超过行的长度 ( len(row) ),减去要从末尾删除的值的数量 ( remove_n_tail )。

There are various methods to achieve similar results.有多种方法可以达到类似的结果。 You might find the Most efficient way to map function over numpy array question interesting.您可能会发现map function 上 numpy 数组问题的最有效方法很有趣。

If arr is your numpy array, rem is a list of removal-counts, a simple solution could be:如果arr是您的numpy数组,则rem是删除计数列表,一个简单的解决方案可能是:

res = [arr[i][:3-rem[i]].tolist() for i in range(len(rem))]

Output: Output:

[[1, 2, 3], [3], [1, 2], [4], [5, 6]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM