python - 索引数组中的两组列

标签 python indexing

我正在尝试从数组中切出列并分配给一个新变量,就像这样。

array1 = array[:,[0,1,2,3,15,16,17,18,19,20]]

有这样的捷径吗?

我试过了,但它抛出了一个错误:

array1 = array[:,[0:3,15:20]]

这可能真的很简单,但我无法在任何地方找到它。

最佳答案

使用np.r_:

Translates slice objects to concatenation along the first axis.

import numpy as np
arr = np.arange(100).reshape(5, 20)
cols = np.r_[:3, 15:20]

print(arr[:, cols])
[[ 0  1  2 15 16 17 18 19]
 [20 21 22 35 36 37 38 39]
 [40 41 42 55 56 57 58 59]
 [60 61 62 75 76 77 78 79]
 [80 81 82 95 96 97 98 99]]

归根结底,可能只比您现在拥有的内容少一点冗长,但可以在更复杂的情况下派上用场。

关于python - 索引数组中的两组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44789577/

相关文章:

python - 如何在 google colab 上升级 pandas

indexing - 在 Polars 中查找 "indexed"的最快方法是什么?

mysql - 如何使现有的自动增量索引成为MySQL中的聚集索引?

java - 线程中的异常 "AWT-EventQueue-0"java.lang.ArrayIndexOutOfBoundsException : 10

python - 预填充 Flask SQLAlchemy 数据库

python - virtualenv 之间莫名其妙的 Urllib2 问题。

python - 访问 cffi 枚举

sql-server - 为此查询在我的表上添加索引

search - 如何将2个过滤器应用于ElasticSearch查询对象?

Python 创建依赖项的 makefile