2

I'm having some difficulty trying to figure out how to do extract multiple values in a list that are spaced some indices apart. For example, given a list l = [0,1,2,3,4,5,6,7,8,9,10], I want to only extract the values [1,2,3] and [6,7,8,9]. I could do l[1:4]+l[6:-1], but is there a way such to write l[1:4,6:-1]?

This is really a ghost problem to the actual problem I am having in a pandas dataframe. I have a dataframe, df, with columns ['A','B','C','I1','D','E','F','I2','I3'], and I only want to keep the important columns ['I1', 'I2', 'I3']. Now, the current approach I am doing is

df.drop(df.columns[0:3], axis=1, inplace=True)
df.drop(df.columns[4:7], axis=1, inplace=True)

Is there a way to do it such that we can do it in 1 line without writing the column values out explicitly?

Thank you!
PS. I know pandas dataframes use numpy, and I haven't found any workarounds in numpy either, but I think the syntax to drop columns is of the standard python list format, if that makes any sense.

EDIT: I found a way to do it for numpy but it is also 2 lines, from this question. We can do:
indices = np.hstack((np.arange(0:3), np.arange(4:7))
df.drop(df.columns[indices], axis=1, inplace=True)

However, I'm still looking for 1-line generalized methods.

2 Answers 2

3

I think you need numpy.r_ for concanecate indices:

print (np.r_[1:4, 6:10])
[1 2 3 6 7 8 9]
Sign up to request clarification or add additional context in comments.

6 Comments

Ah I see! Wow, index_tricks is full of stuff. So this can only work with numpy arrays? Built in python doesn't have anything like this?
Hi, the numpy.r_ function doesn't work with [1:4, 6:-1], because it doesn't have any numpy array to refer to. This means we have to use [1:4, 6:array.shape[0]-1].
Yes, exactly. Another possible solution is [1:4, 6:len(array)-1]
r_ expands the slices into an array of indices. Such an array can't be used to index lists, at least not without a loop or comprehension.
Yes, but then you can use iloc for selecting.
|
0

Using list comprehension, you can do:

>>> [item for item in l[1:4] + l[6:-1]]
[1, 2, 3, 6, 7, 8, 9]

You can also use extend() like this:

>>> res = l[1:4]
>>> res.extend(l[6:-1])
>>> res
[1, 2, 3, 6, 7, 8, 9]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.