从一个QString数组创建numpy数组失败

3
如果数组的大小为2x2或更大,则一切正常,但如果行的维度为1,例如1x2,NumPy会执行我没有预期的操作。该怎么解决?
# TEST 1 OK
myarray = np.array([[QString('hello'), QString('world')],
                    [QString('hello'), QString('moon')]],
                   dtype=object)
print myarray
print myarray.shape
#[[PyQt4.QtCore.QString(u'hello') PyQt4.QtCore.QString(u'world')]
# [PyQt4.QtCore.QString(u'hello') PyQt4.QtCore.QString(u'moon')]]
#(2, 2)


# TEST 2 OK
myarray = np.array([['hello'], ['world']], dtype=object)
print myarray
print myarray.shape  
#[['hello']
# ['world']]
#(2, 1)


# TEST 3 FAIL
myarray = np.array([[QString('hello'), QString('world')]], dtype=object)
print myarray
print myarray.shape
#[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[PyQt4.QtCore.QString(u'h')]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
#..
#[[[[[[[[[[[[[[[[[[[[[[[[[[[[[PyQt4.QtCore.QString(u'e')]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
# etc...
#(1, 2, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

哦,奇怪……几乎看起来像是 numpy 把字符串当作数组处理了什么的……如果在两个闭合方括号之间加上逗号会发生什么? - karina
1个回答

2

尝试使用不同长度的字符串:

np.array([[QString('hello'), QString('moon')]], dtype=object)`.  

使用创建和填充方法来制作对象数组。
A = np.empty((1,2), dtype=object)
A[:] = [QString('hello'), QString('moon')]

我对这些对象不熟悉,但在其他情况下,如果我们尝试从列表构建对象数组,并且列表长度相同,则会变得棘手。如果QString是可迭代的,并且具有类似于.__len__的方法,则可能会发生类似的情况。

我猜你的第一个示例之所以有效,是因为QString比其他字符串短,而不是因为它是2x2。

关于从自定义字典类创建对象数组的最近问题可能与此相关:Override a dict with numpy support


没错,我尝试了第一个例子,如果长度相同就会失败!很好的链接,也许问题的原因与https://dev59.com/Lpbfa4cB1Zd3GeqPpSM-#36666424有关,但我认为你给我的解决方案已经足够了。谢谢! - David Miró

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接