使用:用于列表或numpy数组中的多个切片 [英] Using : for multiple slicing in list or numpy array
问题描述
我很难弄清楚如何提取列表中多个索引分开的多个值.例如,给定一个列表l = [0,1,2,3,4,5,6,7,8,9,10]
,我只想提取值[1,2,3] and [6,7,8,9]
.我可以做l[1:4]+l[6:-1]
,但是有写l[1:4,6:-1]
的方法吗?
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]
?
对于我在熊猫数据框中遇到的实际问题,这确实是一个鬼问题.我有一个数据框df
,其列为['A','B','C','I1','D','E','F','I2','I3']
,而我只想保留重要的列为['I1', 'I2', 'I3']
.现在,我目前正在使用的方法是
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?
谢谢!
PS.我知道pandas数据帧使用numpy,并且在numpy中也没有找到任何解决方法,但是我认为删除列的语法是标准的python列表格式,如果有意义的话.
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.
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)
但是,我仍在寻找1行通用方法.
However, I'm still looking for 1-line generalized methods.
推荐答案
我认为您需要 numpy.r_
用于并置索引:
I think you need numpy.r_
for concanecate indices:
print (np.r_[1:4, 6:10])
[1 2 3 6 7 8 9]
这篇关于使用:用于列表或numpy数组中的多个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!