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.