问题描述
我有一个 48x365 元素的 numpy 数组,其中每个元素都是一个包含 3 个整数的列表.我希望能够将它变成一个 1x17520 的数组,所有列表都完好无损地作为元素.使用
np.reshape(-1)
似乎将元素分解为三个单独的整数并制作一个 1x52560 数组.所以我要么需要一种重新排列原始数组的新方法,要么需要一种将新 np.reshape 数组中的元素(仍按顺序排列)重新分组为 3 的列表的方法.
感谢您的帮助.
您是否有不能明确执行的原因?如:
>>>a = numpy.arange(17520 * 3).reshape(48, 365, 3)>>>a.reshape((17520,3))数组([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],...,[52551, 52552, 52553],[52554, 52555, 52556],[52557、52558、52559]])您也可以使用 -1
来实现,它只需要与另一个适当大小的 arg 配对即可.
或
>>>a.reshape((-1,3))数组([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],...,[52551, 52552, 52553],[52554, 52555, 52556],[52557、52558、52559]])稍后我突然想到您还可以创建一个记录数组——这在某些情况下可能是合适的:
a = numpy.recarray((17520,), dtype=[('x', int), ('y', int), ('z', int)])
这可以按照您尝试的原始方式进行重塑,即 reshape(-1)
.尽管如此,正如 larsmans 的评论所说,将您的数据视为 3d 数组是最简单的.
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)
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.
Thanks for your help.
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]])
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]])
or
>>> 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)])
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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!