Unit 22Transposing and Reshaping

Unlike the great monuments of the past, numpy arrays are not carved in stone. They can easily change their shape and orientation without being called opportunists. Let’s build a one-dimensional array of some S&P stock symbols and twist it in every possible way:

 # Some S&P stock symbols
 sap = np.array([​"MMM"​, ​"ABT"​, ​"ABBV"​, ​"ACN"​, ​"ACE"​, ​"ATVI"​, ​"ADBE"​, ​"ADT"​])
=> array('MMM', 'ABT', 'ABBV', 'ACN', 'ACE', 'ATVI', 'ADBE', 'ADT'],
=>  dtype='<U4')

The function reshape(d0, d1, ...) changes the shape of an existing array. The arguments define the new dimensions. The total number of items in the old and new shapes must be equal: the conservation law still holds in numpyland!

 sap2d = sap.reshape(2, ...

Get Data Science Essentials in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.