简体   繁体   English

numpy .reshape函数更改数组元素类型

[英]numpy .reshape function changes array element type

How can you use the numpy .reshape function on an Array without changing the Array element type in the process? 如何在不更改数组元素类型的情况下在数组上使用numpy .reshape函数? 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 现在,我用.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? 为什么在使用.reshape后,元素类型从字符串更改为数组,如何保持相同的数据类型?

First the letters_array has only one dimension, so when you index it as letters_array[0] you get a single element. 首先, letters_array仅具有一个维度,因此当将其索引为letters_array[0]您将获得一个元素。

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 ). reshape ,数组具有二维,这意味着以相同的方式进行索引将为您提供数组的一行(其类型为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: 与使用type ,最好查看数组的dtype属性,该属性与数组形状无关:

print letters_array.dtype
# |S1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM