Does numpy reshape create a copy? Does numpy reshape create a copy? numpy numpy

Does numpy reshape create a copy?


For Python keep in mind that several variables or names can point to the same object, such as a numpy array. Arrays can also have views, which are new array objects, but with shared data buffers. A copy has its own data buffer.

In [438]: x = np.arange(12)In [439]: y = x                # same objectIn [440]: y.shape = (2,6)      # inplace shape changeIn [441]: yOut[441]: array([[ 0,  1,  2,  3,  4,  5],       [ 6,  7,  8,  9, 10, 11]])In [442]: xOut[442]: array([[ 0,  1,  2,  3,  4,  5],       [ 6,  7,  8,  9, 10, 11]])In [443]: y = y.reshape(3,4)        # y is a new viewIn [444]: yOut[444]: array([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11]])In [445]: xOut[445]: array([[ 0,  1,  2,  3,  4,  5],       [ 6,  7,  8,  9, 10, 11]])

y has a different shape, but shares the data buffer:

In [446]: y += 1In [447]: yOut[447]: array([[ 1,  2,  3,  4],       [ 5,  6,  7,  8],       [ 9, 10, 11, 12]])In [448]: xOut[448]: array([[ 1,  2,  3,  4,  5,  6],       [ 7,  8,  9, 10, 11, 12]])