繁体   English   中英

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

[英]numpy .reshape function changes array element type

如何在不更改数组元素类型的情况下在数组上使用numpy .reshape函数? 这是我的意思:

letters = ['A', 'B', 'C']
letters_array = np.array(letters)
print letters_array
#['A' 'B' 'C']
print type(letters_array[0])
#<type 'numpy.string_'>

现在,我用.reshape

letters_array = letters_array.reshape(3, 1)
print letters_array
#[['A']
#['B']
#['C']]
print type(letters_array[0])
#<type 'numpy.ndarray'>

为什么在使用.reshape后,元素类型从字符串更改为数组,如何保持相同的数据类型?

首先, letters_array仅具有一个维度,因此当将其索引为letters_array[0]您将获得一个元素。

letters = ['A', 'B', 'C']
letters_array = np.array(letters)
print letters_array.ndim
# 1

reshape ,数组具有二维,这意味着以相同的方式进行索引将为您提供数组的一行(其类型为numpy.ndarray )。 要获得单个元素,您必须为每个维度提供一个索引:

letters_array = letters_array.reshape(3, 1)
print letters_array.ndim
# 2
print type(letters_array[0, 0])
# <type 'numpy.string_'>

注意,两种情况下元素类型都是相同的! 与使用type ,最好查看数组的dtype属性,该属性与数组形状无关:

print letters_array.dtype
# |S1

暂无
暂无

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

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