【发布时间】:2020-12-25 19:48:09
【问题描述】:
当用一个字符检查字符串的数据类型时,我得到的 dtype 为 但是在数组中添加一个整数后,为什么会消耗21个字符?print(numpy.array(["a"]).dtype)
Output : <U1
print(numpy.array([1,"a"]).dtype)
Output : <U21
【问题讨论】:
标签: python numpy numpy-dtype
当用一个字符检查字符串的数据类型时,我得到的 dtype 为 但是在数组中添加一个整数后,为什么会消耗21个字符?print(numpy.array(["a"]).dtype)
Output : <U1
print(numpy.array([1,"a"]).dtype)
Output : <U21
【问题讨论】:
标签: python numpy numpy-dtype
因为元素正在被提升,这意味着numpy将元素转换为
type1 和 type1 的最小尺寸和最小标量种类 type2 可以安全地转换。
例如如果我们使用promote_types:
print(np.promote_types('i8', '<U1'))
输出
<U21
关于 U21,它由两部分组成,如您所知,U 表示 Unicode,21 表示它可以容纳的元素数量,请参阅answer 的更多信息。
因此,8 可以转换为 int64,并且它可以容纳至少 20 个字符(尽管取决于平台),它正在转换为 U21。知道一个数字可以包含多少个字符:
ii64 = np.iinfo(np.int64)
print(ii64)
输出
Machine parameters for int64
---------------------------------------------------------------
min = -9223372036854775808
max = 9223372036854775807
---------------------------------------------------------------
特别是:
print(len(str(ii64.min)))
输出
20
您可以通过以下方式保留 U1:
print(np.array(["a", 1]).dtype) # put the string first
输出
<U1
在此 GitHub issue 上查看更多信息。
【讨论】: