在python中重塑numpy数组 [英] Reshaping a numpy array in python

查看:81
本文介绍了在python中重塑numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个48x365元素numpy数组,其中每个元素都是一个包含3个整数的列表.我希望能够将其完整地以元素列表的形式转换为1x17520数组.使用

I have a 48x365 element numpy array where each element is a list containing 3 integers. I want to be able to turn it into a 1x17520 array with all the lists intact as elements. Using

np.reshape(-1)

似乎将元素分成三个独立的整数,并形成1x52560数组.因此,我要么需要一种重新排列原始数组的新方法,要么需要将新的np.reshape数组中的元素分组(仍在顺序中)重新组合为3个列表的方法.

seems to break the elements into three separate integers and makes a 1x52560 array. So I either need a new way of rearranging the original array or a way of grouping the elements in the new np.reshape array (which are still in order) back into lists of 3.

感谢您的帮助.

推荐答案

是否存在无法明确执行此操作的原因?如:

Is there a reason you can't do it explicitly? As in:

>>> a = numpy.arange(17520 * 3).reshape(48, 365, 3)
>>> a.reshape((17520,3))
array([[    0,     1,     2],
       [    3,     4,     5],
       [    6,     7,     8],
       ..., 
       [52551, 52552, 52553],
       [52554, 52555, 52556],
       [52557, 52558, 52559]])

您也可以使用-1进行操作,只需将其与另一个适当大小的arg配对即可.

You could also do it with -1, it just has to be paired with another arg of the appropriate size.

>>> a.reshape((17520,-1))
array([[    0,     1,     2],
       [    3,     4,     5],
       [    6,     7,     8],
       ..., 
       [52551, 52552, 52553],
       [52554, 52555, 52556],
       [52557, 52558, 52559]])

>>> a.reshape((-1,3))
array([[    0,     1,     2],
       [    3,     4,     5],
       [    6,     7,     8],
       ..., 
       [52551, 52552, 52553],
       [52554, 52555, 52556],
       [52557, 52558, 52559]])


稍后我想到您也可以创建一个记录数组-这在某些情况下可能是适当的:


It occurred to me a bit later that you could also create a record array -- this might be appropriate in some situations:

a = numpy.recarray((17520,), dtype=[('x', int), ('y', int), ('z', int)])

这可以按照您尝试的原始方式(即reshape(-1))进行调整.但是,正如larsmans的评论所言,将数据视为3d数组是最简单的.

This can be reshaped in the original way you tried, i.e. reshape(-1). Still, as larsmans' comment says, just treating your data as a 3d array is easiest.

这篇关于在python中重塑numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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