Numpy重塑与余数抛出错误

问题描述 投票:2回答:3

如何将此数组分区为长度为3的数组,并使用填充或未填充的余数(无关紧要)

>>> np.array([0,1,2,3,4,5,6,7,8,9,10])。reshape([3,-1])

ValueError:无法将大小为11的数组重塑为形状(3,newaxis)

arrays python-3.x numpy reshape partitioning
3个回答
2
投票
### Two Examples Without Padding

x = np.array([0,1,2,3,4,5,6,7,8,9,10])
desired_length = 3
num_splits = np.ceil(x.shape[0]/desired_length)

print(np.array_split(x, num_splits))

# Prints:
# [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10])]

x = np.arange(13)
desired_length = 3
num_splits = np.ceil(x.shape[0]/desired_length)

print(np.array_split(x, num_splits))

# Prints:
# [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10]), array([11, 12])]

### One Example With Padding

x = np.arange(13)
desired_length = 3
padding = int(num_splits*desired_length - x.shape[0])
x_pad = np.pad(x, (0,padding), 'constant', constant_values=0)

print(np.split(x_pad, num_splits))

# Prints:
# [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10, 11]), array([12,  0,  0])]

1
投票

如果你想避免用零填充,最优雅的方法可能是在列表理解中切片:

>>> import numpy as np
>>> x = np.arange(11)
>>> [x[i:i+3] for i in range(0, x.size, 3)]
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10])]

0
投票

如果你想用零填充,ndarray.resize()会为你做这个,但你必须自己弄清楚预期数组的大小:

import numpy as np

x = np.array([0,1,2,3,4,5,6,7,8,9,10])

cols = 3
rows = np.ceil(x.size / cols).astype(int)

x.resize((rows, cols))
print(x)

结果如下:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10  0]]

据我所知,这比列表理解方法快了几百倍(参见我的另一个答案)。

请注意,如果您在调整大小之前对x执行任何操作,则可能会遇到“引用”问题。无论是在x.copy()工作还是通过refcheck=Falseresize()

© www.soinside.com 2019 - 2024. All rights reserved.