如何在Python中向numpy数组添加维度 [英] How to add a dimension to a numpy array in Python

查看:652
本文介绍了如何在Python中向numpy数组添加维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为(214,144)的数组.我需要它是(214,144,1)有没有办法在Python中轻松做到这一点?基本上,尺寸应为(天,时,站).由于我只有1个工作站的数据,因此维度将为1.但是,如果我也可以使代码足够灵活地工作,例如2个工作站就可以了(例如,将维度大小从(428,288)更改为(214,144,2))那就太好了!

I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 stations that would be great (e.g. changing the dimension size from (428,288) to (214,144,2)) that would be great!

推荐答案

您可以使用 reshape :

You could use reshape:

>>> a = numpy.array([[1,2,3,4,5,6],[7,8,9,10,11,12]])
>>> a.shape
(2, 6)
>>> a.reshape((2, 6, 1))
array([[[ 1],
        [ 2],
        [ 3],
        [ 4],
        [ 5],
        [ 6]],

       [[ 7],
        [ 8],
        [ 9],
        [10],
        [11],
        [12]]])
>>> _.shape
(2, 6, 1)

除了将形状从(x, y)更改为(x, y, 1)外,您还可以使用(x, y/n, n),但是您可能要根据输入指定列顺序:

Besides changing the shape from (x, y) to (x, y, 1), you could use (x, y/n, n) as well, but you may want to specify the column order depending on the input:

>>> a.reshape((2, 3, 2))
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6]],

       [[ 7,  8],
        [ 9, 10],
        [11, 12]]])
>>> a.reshape((2, 3, 2), order='F')
array([[[ 1,  4],
        [ 2,  5],
        [ 3,  6]],

       [[ 7, 10],
        [ 8, 11],
        [ 9, 12]]])

这篇关于如何在Python中向numpy数组添加维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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