gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:37:14 25 4
gpt4 key购买 nike

如何在不更改数组元素类型的情况下对数组使用 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

关于python - numpy .reshape 函数更改数组元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22715350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com