3

If the array has a size of 2x2 or greater all is well, but if the dimension of the row is 1, for example 1x2, numpy does something I did not expect.

How can I solve this?

# 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)
David Miró
  • 2,694
  • 20
  • 20
  • Oh weird... Almost seems like numpy is treating the strings as arrays or something... What happens if you put a comma between the 2 closing square brackets? – karina Apr 29 '16 at 07:10

1 Answers1

2

Try different length strings:

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

or the create and fill approach to making an object array

A = np.empty((1,2), dtype=object)
A[:] = [QString('hello'), QString('moon')]

I'm not familiar with these objects, but in other cases where we try to build object arrays from lists, it is tricky if the lists are the same length. If QString is iterable, with a .__len__ something similar may be happening.

I'm guessing your first example works because on QString is shorter than the others, not because it is 2x2.

This recent question about making an object array from a custom dictionary class may be relevant: Override a dict with numpy support

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • It is true, I tried the first example and fails if the lengths are identicals!. Good link, maybe the cause of the problem it's related with http://stackoverflow.com/a/36666424/2270217 , but I think that your solution for me it's enough Thank you! – David Miró Apr 29 '16 at 08:08