使用 : 用于列表或 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]
?
对于我在 pandas 数据帧中遇到的实际问题,这确实是一个幽灵问题。我有一个数据框 df
,列 ['A','B','C','I1','D','E','F','I2','I3']
,我只想保留重要的列 ['I1', 'I2', 'I3']
。现在,我目前正在做的方法是
df.drop(df.columns[0:3], axis=1, inplace=True)
df.drop(df.columns[4:7], axis=1, inplace=True)
有没有一种方法可以在一行中完成而不用显式写出列值?
谢谢!
PS。我知道 pandas 数据帧使用 numpy,我也没有在 numpy 中找到任何解决方法,但我认为删除列的语法是标准的 python 列表格式,如果这有意义的话。
编辑: 我找到了一种为 numpy 做的方法,但它也是 2 行,来自 this question。我们可以做到:
indices = np.hstack((np.arange(0:3), np.arange(4:7))
df.drop(df.columns[indices], axis=1, inplace=True)
但是,我仍在寻找 1 行通用方法。
我认为您需要 numpy.r_
用于连接索引:
print (np.r_[1:4, 6:10])
[1 2 3 6 7 8 9]
使用列表理解,您可以:
>>> [item for item in l[1:4] + l[6:-1]]
[1, 2, 3, 6, 7, 8, 9]
你也可以这样使用extend()
:
>>> res = l[1:4]
>>> res.extend(l[6:-1])
>>> res
[1, 2, 3, 6, 7, 8, 9]
我在尝试弄清楚如何在列表中提取多个索引间隔开的多个值时遇到了一些困难。例如,给定一个列表 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]
?
对于我在 pandas 数据帧中遇到的实际问题,这确实是一个幽灵问题。我有一个数据框 df
,列 ['A','B','C','I1','D','E','F','I2','I3']
,我只想保留重要的列 ['I1', 'I2', 'I3']
。现在,我目前正在做的方法是
df.drop(df.columns[0:3], axis=1, inplace=True)
df.drop(df.columns[4:7], axis=1, inplace=True)
有没有一种方法可以在一行中完成而不用显式写出列值?
谢谢!
PS。我知道 pandas 数据帧使用 numpy,我也没有在 numpy 中找到任何解决方法,但我认为删除列的语法是标准的 python 列表格式,如果这有意义的话。
编辑: 我找到了一种为 numpy 做的方法,但它也是 2 行,来自 this question。我们可以做到:
indices = np.hstack((np.arange(0:3), np.arange(4:7))
df.drop(df.columns[indices], axis=1, inplace=True)
但是,我仍在寻找 1 行通用方法。
我认为您需要 numpy.r_
用于连接索引:
print (np.r_[1:4, 6:10])
[1 2 3 6 7 8 9]
使用列表理解,您可以:
>>> [item for item in l[1:4] + l[6:-1]]
[1, 2, 3, 6, 7, 8, 9]
你也可以这样使用extend()
:
>>> res = l[1:4]
>>> res.extend(l[6:-1])
>>> res
[1, 2, 3, 6, 7, 8, 9]