Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

python - How do I get all the values from a NumPy array excluding a certain index?

I have a NumPy array, and I want to retrieve all the elements except a certain index. For example, consider the following array

a = [0,1,2,3,4,5,5,6,7,8,9]

If I specify index 3, then the resultant should be

a = [0,1,2,4,5,5,6,7,8,9]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like resizing, removing elements from an NumPy array is a slow operation (especially for large arrays since it requires allocating space and copying all the data from the original array to the new array). It should be avoided if possible.

Often you can avoid it by working with a masked array instead. For example, consider the array a:

import numpy as np

a = np.array([0,1,2,3,4,5,5,6,7,8,9])
print(a)
print(a.sum())
# [0 1 2 3 4 5 5 6 7 8 9]
# 50

We can mask its value at index 3 and can perform a summation which ignores masked elements:

a = np.ma.array(a, mask=False)
a.mask[3] = True
print(a)
print(a.sum())
# [0 1 2 -- 4 5 5 6 7 8 9]
# 47

Masked arrays also support many operations besides sum.

If you really need to, it is also possible to remove masked elements using the compressed method:

print(a.compressed())
# [0 1 2 4 5 5 6 7 8 9]

But as mentioned above, avoid it if possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...