Python 实现取多维数组第n维的前几位

yipeiwu_com6年前Python基础

现在我们有一个shape为(7352, 9, 128, 1)的numpy数组。

想要取出第2维的前三个数据,构成新数组(7352, 3, 128, 1)

我的思想是:将第2维数据转置(transpose)到第一维,再用切片(slice)取出前三个数据,再转置回去:

print("# original", input.shape)
input_transpose = input.transpose((1, 0, 2, 3))
print("# transpose", input_transpose.shape)
input_slice = input_transpose[0:3]
print("# slice", input_slice.shape)
output = input_slice.transpose((1, 0, 2, 3))
print("# output", output.shape)

其实更简单的做法是:

print("# original", input.shape)
print("# output", input[:, [0, 1, 2]].shape)

以上这篇Python 实现取多维数组第n维的前几位就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python异常的检测和处理方法

捕获异常 # 对数字变量使用append操作 a = 123 a.apppend(4) 执行这个程序时,会抛出: AttributeError: 'int' object h...

Python中defaultdict与lambda表达式用法实例小结

本文实例讲述了Python中defaultdict与lambda表达式用法。分享给大家供大家参考,具体如下: 从教程中看到defaultdict是一个类,在一台装有Python2.7.6...

python画蝴蝶曲线图的实例

python画蝴蝶曲线图的实例

蝴蝶曲线是由Temple H·Fay发现的可用极坐标函数表示的蝴蝶曲线。 由于此曲线优美, 因此就想把它作为博客favicon.ico,这里我使用pytho matplotlib.pyp...

Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str

在python的Beautiful Soup 4 扩展库的使用过程中出现了 TypeError: list indices must be integers or slices, no...

Python3列表内置方法大全及示例代码小结

Python3列表内置方法大全及示例代码小结

Python中的列表是简直可说是有容乃大,虽然看似类似C中的数组,但是Python列表可以接受任意的对象元素,比如,字符串,数字,布尔值,甚至列表,字典等等,自由度提升到一个新的高度,而...