在 Python 中选择一系列列 [英] Selecting a range of columns in Python

查看:38
本文介绍了在 Python 中选择一系列列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 0 到 10 列组成的数据集,我想提取仅在 1 到 5 列而不是 6 和 7 到 9 列中的信息(这意味着不是最后一列).到目前为止,我已经完成了以下工作:

I have a dataset that consist of columns 0 to 10, and I want to extract the information that is only in columns 1 to 5, not 6, and 7 to 9 (it means not the last one). So far, I have done the following:

 A=B[:,[[1:5],[7:-1]]]

但是我遇到了语法错误,我该如何获取该数据?

but I got a syntax error, how can I get that data?

谢谢

推荐答案

高级索引不采用切片列表的列表.相反,您可以使用 numpy.r_.此函数不采用负索引,但您可以使用 np.ndarray.shape:

Advanced indexing doesn't take a list of lists of slices. Instead, you can use numpy.r_. This function doesn't take negative indices, but you can get round this by using np.ndarray.shape:

A = B[:, np.r_[1:6, 7:B.shape[1]-1]]

记得给第二部分加1,因为a:b不包括b,同理slice(a, b) 不包括 b.另请注意,索引从 0 开始.

Remember to add 1 to the second part, since a: b does not include b, in the same way slice(a, b) does not include b. Also note that indexing begins at 0.

这是一个演示:

import numpy as np

B = np.random.randint(0, 10, (3, 11))

print(B)

[[5 8 8 8 3 0 7 2 1 6 7]
 [4 3 8 7 3 7 5 6 0 5 7]
 [1 0 4 0 2 2 5 1 4 2 3]]

A = B[:,np.r_[1:6, 7:B.shape[1]-1]]

print(A)

[[8 8 8 3 0 2 1 6]
 [3 8 7 3 7 6 0 5]
 [0 4 0 2 2 1 4 2]]

这篇关于在 Python 中选择一系列列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆