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

标签 python string numpy

我正在尝试确定 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 safe 也将测试转换是否会导致截断),但仍然没有真正解决测试字符大小的问题。

最佳答案

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字节)。

关于python - 获取 numpy unicode 字符串 dtype 长度的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120878/

相关文章:

python - python selenium chrome headless中的文件下载路径设置不适用

python - Pandas Dataframe Append 或 Set_Value

c - 如何在c中实现计数hashmap?

Purescript 中的字符串连接

c# - 无法将类型 'String' 转换为 'Int' ?

python - 在 numpy 数组中查找有序向量

python - 如何正确运行 setup.py 文件?

c++ - boost::python 和 swig 集成

Python3 : writing csv files

python - 提取numpy数组中的特定列