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.
I think you need numpy.r_
for concanecate indices:
print (np.r_[1:4, 6:10])
[1 2 3 6 7 8 9]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.