Skip to main content
 首页 » 编程设计

python之获取numpy unicode字符串dtype长度的最佳方法

2024年11月01日23zhujiabin

我正在尝试确定 numpy unicode 数组的最大元素长度。例如,如果我有:

# (dtypes added for clarity) 
a = np.array(['a'], dtype='U5') 
print(get_dtype_length(a)) 

我希望它打印5。

我可以这样做:

def get_dtype_length(a): 
  dtype = a.dtype 
  dtype_string = dtype.descr[0][1]  # == '<U5' 
  length = int(dtype_string[2:]) 
  return length 

但这似乎是一种迂回的方式来推断某处必须可用的东西。是否有我没有找到的属性或 numpy 函数可以直接执行此操作?

基于评论的澄清:

我专门寻找数组中任何元素的最大允许长度,而不是任何特定元素的长度(例如,不是 len(a[0]) == 1。动机这背后的原因是,如果我尝试通过类似 a[0] = 'string_longer_than_dtype_of_a' 的方式更新 a,我不希望元素被截断为 stri。

在 numpy 版本 1.19 中,我相信 np.can_cast(newVal.dtype, a.dtype, casting='safe') 将是对我的用例的有效测试(因为在 1.19 中安全也将测试转换是否导致截断),但它仍然没有真正解决测试字符大小的问题。

请您参考如下方法:

U4中的4是每个元素的字符串长度,不是字符的大小:

The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters.

来自 the docs .

单个 Unicode 字符的大小在您的程序中可以是常量:

 sizeof_numpy_unicode_char = np.dtype('U1').itemsize 

然后,您可以使用 dtype.itemsize 将每个元素的总字节数除以该常量以获得缓冲区大小。 , 或快捷方式 ndarray.itemsize :

def get_length(a): 
    return a.itemsize // sizeof_numpy_unicode_char 

但是字符的大小确实是固定的(通常是4个字节)。