Using : for multiple slicing in list or numpy array

余生颓废 提交于 2019-12-02 02:41:33

问题


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.


回答1:


I think you need numpy.r_ for concanecate indices:

print (np.r_[1:4, 6:10])
[1 2 3 6 7 8 9]



回答2:


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]


来源:https://stackoverflow.com/questions/40970197/using-for-multiple-slicing-in-list-or-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!