python改变数组维度,如何在Python中向numpy数组添加维度

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!

解决方案

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)

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]]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值