recarray 中的自动字符串长度 [英] Automatic string length in recarray

查看:51
本文介绍了recarray 中的自动字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我以这种方式创建一个重新数组:

If I create a recarray in this way:

In [29]: np.rec.fromrecords([(1,'hello'),(2,'world')],names=['a','b'])

结果看起来不错:

Out[29]: 
rec.array([(1, 'hello'), (2, 'world')], 
      dtype=[('a', '<i8'), ('b', '|S5')])

但是如果我想指定数据类型:

But if I want to specify the data types:

In [32]: np.rec.fromrecords([(1,'hello'),(2,'world')],dtype=[('a',np.int8),('b',np.str)])

字符串的长度设置为零:

The string is set to a length of zero:

Out[32]: 
rec.array([(1, ''), (2, '')], 
      dtype=[('a', '|i1'), ('b', '|S0')])

我需要为所有数字类型指定数据类型,因为我关心 int8/16/32 等,但我想从自动字符串长度检测中受益,如果我不指定数据类型,它会起作用.我尝试用 None 替换 np.str 但没有运气.例如,我知道我可以指定 '|S5',但我事先不知道应该将字符串长度设置为什么.

I need to specify datatypes for all numerical types since I care about int8/16/32, etc, but I would like to benefit from the auto string length detection that works if I don't specify datatypes. I tried replacing np.str by None but no luck. I know I can specify '|S5' for example, but I don't know in advance what the string length should be set to.

推荐答案

如果您不需要将字符串作为字节进行操作,您可以使用对象数据类型来表示它们.这实际上存储了一个指针而不是实际的字节:

If you don't need to manipulate the strings as bytes, you may use the object data-type to represent them. This essentially stores a pointer instead of the actual bytes:

In [38]: np.array(data, dtype=[('a', np.uint8), ('b', np.object)])
Out[38]: 
array([(1, 'hello'), (2, 'world')], 
      dtype=[('a', '|u1'), ('b', '|O8')])

或者,Alex 的想法也行得通:

Alternatively, Alex's idea would work well:

new_dt = []

# For each field of a given type and alignment, determine
# whether the field is an integer.  If so, represent it as a byte.

for f, (T, align) in dt.fields.iteritems():
    if np.issubdtype(T, int):
        new_dt.append((f, np.uint8))
    else:
        new_dt.append((f, T))

new_dt = np.dtype(new_dt)
np.array(data, dtype=new_dt)

哪个应该产生

array([(1, 'hello'), (2, 'world')], 
      dtype=[('f0', '|u1'), ('f1', '|S5')])

这篇关于recarray 中的自动字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆