193

numpy 配列の最初の次元の一部のみを「サブフラット化」またはフラット化する簡単な方法はありますか?

たとえば、次元のnumpy配列が与えられた場合(50,100,25)、結果の次元は次のようになります(5000,25)

4

4 に答える 4

179

numpy.reshapeを見てください。

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)
于 2013-09-12T07:27:33.007 に答える
104

アレクサンダーの答えのわずかな一般化 - np.reshape は引数として -1 を取ることができます。これは、「配列の合計サイズを他のすべてのリストされた次元の積で割った値」を意味します。

たとえば、最後の次元を除くすべてを平坦化するには:

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
于 2014-10-24T18:14:30.337 に答える
3

別のアプローチは、次のように使用することnumpy.resize()です。

In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)

# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True
于 2019-04-23T02:30:17.183 に答える