当尝试连接具有dtype字符串但具有不同长度的字段的记录数组时,连接失败.
正如您在下面的示例中所看到的,如果'f1'具有相同的长度但是失败则连接起作用,否则失败.
In [1]: import numpy as np
In [2]: a = np.core.records.fromarrays( ([1,2], ["one","two"]) )
In [3]: b = np.core.records.fromarrays( ([3,4,5], ["three","four","three"]) )
In [4]: c = np.core.records.fromarrays( ([6], ["six"]) )
In [5]: np.concatenate( (a,c) )
Out[5]:
array([(1, 'one'), (2, 'two'), (6, 'six')],
dtype=[('f0', '<i8'), ('f1', '|S3')])
In [6]: np.concatenate( (a,b) )
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/u/jegannas/<ipython console> in <module>()
TypeError: expected a readable buffer object
Run Code Online (Sandbox Code Playgroud)
但是,如果我们只是连接数组(而不是记录),它会成功,尽管字符串的大小不同.
In [8]: np.concatenate( (a['f1'], b['f1']) )
Out[8]:
array(['one', 'two', 'three', 'four', 'three'],
dtype='|S5')
Run Code Online (Sandbox Code Playgroud)
这是连接记录时连接的错误还是预期的行为.我只想通过以下方法来克服这个问题.
In [10]: np.concatenate( (a.astype(b.dtype), b) )
Out[10]:
array([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'three')],
dtype=[('f0', '<i8'), ('f1', '|S5')]
Run Code Online (Sandbox Code Playgroud)
但麻烦在于我必须经历所有的重组,我连接并找到最大的字符串长度,我必须使用它.如果我在记录数组中有多个字符串列,我还需要跟踪其他一些事情.
您认为克服这一点的最佳方法是什么,至少现在如此?
发表完整的答案.正如Pierre GM所建议的那样:
import numpy.lib.recfunctions
Run Code Online (Sandbox Code Playgroud)
给出了解决方案.然而,做你想要的功能是:
numpy.lib.recfunctions.stack_arrays((a,b), autoconvert=True, usemask=False)
Run Code Online (Sandbox Code Playgroud)
(usemask=False只是为了避免屏蔽数组,你可能不会使用的创建.重要的是autoconvert=True,从强制转换a的dtype "|S3"到"|S5").