[英]delete all columns of a dimension except for a specific column
I want to make a function which takes a n-dimensional array, the dimension and the column index, and it will return the (n-1)-dimensional array after removing all the other columns of that specific dimension. 我想制作一个函数,该函数需要一个n维数组,维和列索引,在删除该特定维的所有其他列之后,它将返回(n-1)维数组。
Here is the code I am using now 这是我现在正在使用的代码
a = np.arange(6).reshape((2, 3)) # the n-dimensional array
axisApplied = 1
colToKeep = 0
colsToDelete = np.delete(np.arange(a.shape[axisApplied]), colToKeep)
a = np.squeeze(np.delete(a, colsToDelete, axisApplied), axis=axisApplied)
print(a)
# [0, 3]
Note that I have to manually calculate the n-1 indices (the complement of the specific column index) to use np.delete(), and I am wondering whether there is a more convenient way to achieve my goal, eg specify which column to keep directly. 请注意,我必须手动计算n-1个索引(特定列索引的补数)才能使用np.delete(),并且我想知道是否有更方便的方法来实现我的目标,例如,指定要访问的列直接保留。
Thank you for reading and I am welcome to any suggestions. 感谢您的阅读,欢迎提出任何建议。
In [1]: arr = np.arange(6).reshape(2,3)
In [2]: arr
Out[2]:
array([[0, 1, 2],
[3, 4, 5]])
Simple indexing: 简单索引:
In [3]: arr[:,0]
Out[3]: array([0, 3])
Or if you need to used the general axis
parameter, try take
: 或者,如果需要使用通用
axis
参数,请尝试take
:
In [4]: np.take(arr,0,axis=1)
Out[4]: array([0, 3])
Picking one element, or a list of elements, along an axis is a lot easier than deleting some. 沿轴选取一个元素或元素列表要比删除某些元素容易得多。 Look at the code for
np.delete
. 查看
np.delete
的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.