Reputation: 25023
In [31]: print(np.poly1d((3,2)))
3 x + 2
In [32]: a = np.array(( np.poly1d((3,2)), np.poly1d((3,2)) ))
I expected that array a
were a (2,)
shaped array of numpy.lib.polynomial.poly1d
objects, BUT
In [33]: a.shape
Out[33]: (2, 2)
In [34]: type(a[0,0])
Out[34]: numpy.int64
In [35]: a
Out[35]:
array([[2, 2],
[2, 2]])
What's going on?
It's worth to be mentioned that
In [36]: a = np.array(( np.poly1d((3,2,1)), np.poly1d((3,2,1)) ))
raises an error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-38-3139075221f6> in <module>
----> 1 a = np.array(( np.poly1d((3,2,1)), np.poly1d((3,2,1)), np.poly1d((3,2,1)) ))
ValueError: cannot copy sequence with size 2 to array axis with dimension 3
Upvotes: 0
Views: 214
Reputation: 231385
A poly1d
object is iterable
In [1]: np.poly1d((3,2))
Out[1]: poly1d([3, 2])
In [2]: list(_)
Out[2]: [3, 2]
np.array
tries to makes a multidimensional numeric array from its inputs, iterating where possible. That's why making an array from these poly1d
object ends up looking like you did np.array([[3,2],[3,2]])
.
The most reliable way to create an object dtype array is to initialize a 'blank' one and fill it.
In [12]: arr = np.empty(2, object)
In [13]: arr[:] = [np.poly1d((3,2)), np.poly1d((4,2))]
In [14]: arr
Out[14]: array([poly1d([3, 2]), poly1d([4, 2])], dtype=object)
But do you really need an object dtype array? Why not stick with a list of the poly1d
objects?
===
We've observed in other SO that attempting to create a object dtype array can go several different ways. Some times it works, sometimes you get a numeric array, and sometimes an error.
In [17]: np.array([np.poly1d((3,2)), np.poly1d((3,2,1))])
Out[17]: array([poly1d([3, 2]), poly1d([3, 2, 1])], dtype=object)
In [18]: np.array([np.poly1d((3,2,1)), np.poly1d((3,2,1))])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-18-00b20d14a2b6> in <module>
----> 1 np.array([np.poly1d((3,2,1)), np.poly1d((3,2,1))])
ValueError: cannot copy sequence with size 2 to array axis with dimension 3
Upvotes: 1