Trying to recreate your case:
In [182]: a,b,c = 0,1,2
In [183]: metric1, metric2 = 100,200
In [186]: data = [
...: [ 1, a, [metric1, metric2] ],
...: [ 1, b, [metric1, metric2] ],
...: [ 2, b, [metric1, metric2] ],
...: [ 2, c, [metric1, metric2] ],
...: [ 3, a, [metric1, metric2] ],
...: [ 3, c, [metric1, metric2] ],
...: ]
In [187]:
In [187]: data
Out[187]:
[[1, 0, [100, 200]],
[1, 1, [100, 200]],
[2, 1, [100, 200]],
[2, 2, [100, 200]],
[3, 0, [100, 200]],
[3, 2, [100, 200]]]
In [189]: data = np.array(data,object)
In [190]: rows, row_pos = np.unique(data[:, 0], return_inverse=True)
...: cols, col_pos = np.unique(data[:, 1], return_inverse=True)
...: pivot_table = np.zeros((len(rows), len(cols)), dtype=object)
In [191]: pivot_table
Out[191]:
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=object)
In [192]: pivot_table[row_pos, col_pos] = data[:, 2]
In [193]: pivot_table
Out[193]:
array([[list([100, 200]), list([100, 200]), 0],
[0, list([100, 200]), list([100, 200])],
[list([100, 200]), 0, list([100, 200])]], dtype=object)
In [194]: pivot_table[row_pos, col_pos]
Out[194]:
array([list([100, 200]), list([100, 200]), list([100, 200]),
list([100, 200]), list([100, 200]), list([100, 200])], dtype=object)
In [195]: _.shape
Out[195]: (6,)
In [196]: data[:,2].shape
Out[196]: (6,)
This assignment works between the source shape (and dtype) matches the target's (6,).
In [197]: mask = pivot_table==0
In [198]: mask
Out[198]:
array([[False, False, True],
[ True, False, False],
[False, True, False]])
In [199]: pivot_table[mask]
Out[199]: array([0, 0, 0], dtype=object)
In [200]: pivot_table[mask] = [0,0]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-200-83e0a7422802> in <module>()
----> 1 pivot_table[mask] = [0,0]
ValueError: NumPy boolean array indexing assignment cannot assign 2 input values to the 3 output values where the mask is true
Different error message (different numpy version?), but this says I'm trying to put 2 values into 3 slots. It doesn't treat the [0,0] as a single item, but as 2.
No problem assigning a scalar element:
In [203]: pivot_table[mask] = None
In [204]: pivot_table
Out[204]:
array([[list([100, 200]), list([100, 200]), None],
[None, list([100, 200]), list([100, 200])],
[list([100, 200]), None, list([100, 200])]], dtype=object)
In the past I've had success using frompyfunc to create object dtype arrays. Define a little function. I could have tested for 0 or type, but since I've already inserted None, let's test for that:
In [205]: def fun(x):
...: if x is None: return [0,0]
...: return x
Apply it to each element of pivot_table, producing a new array.
In [230]: arr1 = np.frompyfunc(fun,1,1)(pivot_table)
In [231]: arr1
Out[231]:
array([[list([100, 200]), list([100, 200]), list([0, 0])],
[list([0, 0]), list([100, 200]), list([100, 200])],
[list([100, 200]), list([0, 0]), list([100, 200])]], dtype=object)
Another approach, let's try to assign a list of lists:
In [240]: pivot_table[mask] = [[0,0] for _ in range(3)]
TypeError: NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions
But if I try the same thing with where, it works:
In [241]: pivot_table[np.where(mask)] = [[0,0] for _ in range(3)]
In [242]: pivot_table
Out[242]:
array([[list([100, 200]), list([100, 200]), list([0, 0])],
[list([0, 0]), list([100, 200]), list([100, 200])],
[list([100, 200]), list([0, 0]), list([100, 200])]], dtype=object)
With where it's more like your original assignment to pivot_table.
In [243]: np.where(mask)
Out[243]: (array([0, 1, 2]), array([2, 0, 1]))
This array indexing still can have problems with broadcasting,
In [244]: pivot_table[np.where(mask)] = [0,0]
ValueError: cannot copy sequence with size 2 to array axis with dimension 3
Usually boolean mask index behaves like the equivalent np.where(mask) indexing, but evidently here, the interplay of object dtype, and broadcasting messes with the boolean indexing.
Out[231] is still a (3,3) array, even though all elements a len 2 lists. To turn it into a numeric array we have to do something like:
In [248]: p = np.stack(pivot_table.ravel()).reshape(3,3,2)
In [249]: p
Out[249]:
array([[[100, 200],
[100, 200],
[ 0, 0]],
[[ 0, 0],
[100, 200],
[100, 200]],
[[100, 200],
[ 0, 0],
[100, 200]]])
np.concatenate (and *stack versions) can join lists into an array, but it has to start with a list or flat array, hence the need for ravel and reshape.
np.array(pivot_table.tolist()) also works.
If instead you'd constructed a structured data array (assuming the metric values are numeric):
In [265]: data1 = np.array([tuple(x.tolist()) for x in data],'i,i,2i')
In [266]: data1
Out[266]:
array([(1, 0, [100, 200]), (1, 1, [100, 200]), (2, 1, [100, 200]),
(2, 2, [100, 200]), (3, 0, [100, 200]), (3, 2, [100, 200])],
dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4', (2,))])
In [267]: data1['f2']
Out[267]:
array([[100, 200],
[100, 200],
[100, 200],
[100, 200],
[100, 200],
[100, 200]], dtype=int32)
these values could be assigned to a 3d pivot_table:
In [268]: p = np.zeros((len(rows), len(cols),2),int)
In [269]: p[row_pos, col_pos]=data1['f2']
With the fillvalue array that Paul Panzer defined, your initial masked assignment works:
In [322]: fillvalue = np.empty((), 'O')
...: fillvalue[()] = [0, 0]
...:
In [323]: fillvalue
Out[323]: array(list([0, 0]), dtype=object)
In [324]: mask
Out[324]:
array([[False, False, True],
[ True, False, False],
[False, True, False]])
In [325]: pivot_table[mask] = fillvalue
His full does a np.copyto(a, fill_value, casting='unsafe'),
Our masked assignment could be written as: np.copyto(pivot_table, fillvalue, where=mask)
pivot_table[pivot_table == 0]. It's probably a 1d array of 0s. Assigning a scalar, or object likeNoneto those locations should work fine. But assigning a list will be tricky.numpywill convert the list tondarrayand then try to apply broadcasting. In general. Assigning a list to a single element of an object array works fine, but assigning to multiple ones is hard.list([metric1, metric2])for each item. I've tried just having a standard 2D array, but then I would only be able to pivot one of the metrics. I suppose a solution would be to create individual tables for each metric, then merge them into one afterwards.