[Numpy-discussion] two dimensional array of sets

David Warde-Farley dwf at cs.toronto.edu
Thu Aug 12 20:18:55 EDT 2010


On 2010-08-12, at 5:54 PM, gerardob wrote:

> As i wrote, the elements of each A[i][j] are sets and not numbers.

Ah, missed that part.

Assuming you don't need/want these sets to be mutable or differently sized, you could do something like this.

Here we make 'n' an array of the numbers 0 to 49, but you could do other things. We immediately reshape it to a 3D array with the 50 elements being the "depth" dimension.

>>>> n = np.arange(50).reshape(1, 1, 50)
>>>> i, j, _ = np.ogrid[1:6, 1:6, 0:1] # adding a dummy dimension

Look in the NumPy docs about "broadcasting" to see why this works the way it does, also have a gander at the contents of the i and j arrays and their .shape properties.

>>>> arr = i**n * j*5 - n
>>>> print arr[0, 0]

[  5   4   3   2   1   0  -1  -2  -3  -4  -5  -6  -7  -8  -9 -10 -11 -12
 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30
 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44]

If you want the sets to be proper Python sets then you might want to look at Ben's reply, but you can accomplish many operations on sets using 1-d NumPy arrays. Have a look at help(np.lib.arraysetops) for a list of functions. 

Also, NumPy can only work with fixed-size data types so if you need to work with numbers bigger than 2^63 - 1 (or smaller than -2^63) than you ought to use Ben's method.

David

David


More information about the NumPy-Discussion mailing list