Reputation: 1185
How can you use the numpy .reshape function on an Array without changing the Array element type in the process? Here is what I mean:
letters = ['A', 'B', 'C']
letters_array = np.array(letters)
print letters_array
#['A' 'B' 'C']
print type(letters_array[0])
#<type 'numpy.string_'>
now, I use .reshape
letters_array = letters_array.reshape(3, 1)
print letters_array
#[['A']
#['B']
#['C']]
print type(letters_array[0])
#<type 'numpy.ndarray'>
Why does the element type change from a string to an array after using .reshape and how can one keep the same data type?
Upvotes: 1
Views: 1778
Reputation:
First the letters_array
has only one dimension, so when you index it as letters_array[0]
you get a single element.
letters = ['A', 'B', 'C']
letters_array = np.array(letters)
print letters_array.ndim
# 1
After the reshape
the array has two dimensions, meaning indexing in the same way gives you a row of the array (which has type numpy.ndarray
). To get a single element you have to supply one index for each dimension:
letters_array = letters_array.reshape(3, 1)
print letters_array.ndim
# 2
print type(letters_array[0, 0])
# <type 'numpy.string_'>
Note that the element type is the same on both occasions! Instead of using type
it's better to look at the dtype
property of the array, which is independent of array shape:
print letters_array.dtype
# |S1
Upvotes: 4