Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

arrays - Selecting a range of columns in Python

I have a dataset that consist of columns 0 to 10, and I want to extract the information that is only in columns 1 to 5, not 6, and 7 to 9 (it means not the last one). So far, I have done the following:

 A=B[:,[[1:5],[7:-1]]]

but I got a syntax error, how can I get that data?

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Advanced indexing doesn't take a list of lists of slices. Instead, you can use numpy.r_. This function doesn't take negative indices, but you can get round this by using np.ndarray.shape:

A = B[:, np.r_[1:6, 7:B.shape[1]-1]]

Remember to add 1 to the second part, since a: b does not include b, in the same way slice(a, b) does not include b. Also note that indexing begins at 0.

Here's a demo:

import numpy as np

B = np.random.randint(0, 10, (3, 11))

print(B)

[[5 8 8 8 3 0 7 2 1 6 7]
 [4 3 8 7 3 7 5 6 0 5 7]
 [1 0 4 0 2 2 5 1 4 2 3]]

A = B[:,np.r_[1:6, 7:B.shape[1]-1]]

print(A)

[[8 8 8 3 0 2 1 6]
 [3 8 7 3 7 6 0 5]
 [0 4 0 2 2 1 4 2]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...