简体   繁体   English

使用:用于列表或numpy数组中的多个切片

[英]Using : for multiple slicing in list or numpy array

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] . 例如,给定列表l = [0,1,2,3,4,5,6,7,8,9,10] ,我只想提取值[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] ? 我可以做l[1:4]+l[6:-1] ,但是有写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'] . 我有一个数据框df ,其列为['A','B','C','I1','D','E','F','I2','I3']和想要保留重要的列['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. 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. 我知道pandas数据帧使用numpy,也没有在numpy中找到任何解决方法,但是我认为删除列的语法是标准的python列表格式,如果有的话。

EDIT: I found a way to do it for numpy but it is also 2 lines, from this question . 编辑:我找到了一种方法来为numpy做到这一点,但从这个问题也是2行。 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: 我认为您需要numpy.r_来合并索引:

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: 您也可以像这样使用extend()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM