Assuming A
has the data stored as a 2D numpy array
, you can do something like this -
unqA = np.unique(A[:,0])
out = {unqA[i]:A[A[:,0]==unqA[i],1:] for i in range(len(unqA))}
Sample run -
In [109]: A
Out[109]:
array([[1, 0, 0, 3, 4, 5],
[3, 0, 0, 9, 0, 0],
[5, 0, 0, 2, 2, 2],
[1, 0, 1, 5, 0, 0],
[5, 0, 1, 3, 0, 0],
[5, 1, 0, 0, 4, 0]])
In [110]: unqA = np.unique(A[:,0])
In [111]: {unqA[i]:A[A[:,0]==unqA[i],1:] for i in range(len(unqA))}
Out[111]:
{1: array([[0, 0, 3, 4, 5],
[0, 1, 5, 0, 0]]),
3: array([[0, 0, 9, 0, 0]]),
5: array([[0, 0, 2, 2, 2],
[0, 1, 3, 0, 0],
[1, 0, 0, 4, 0]])}
If you are okay with a list of such matrices as the output, you could avoid looping like so -
sortedA = A[A[:,0].argsort()]
_,idx = np.unique(sortedA[:,0],return_index=True)
out = np.split(sortedA[:,1:],idx[1:],axis=0)
Sample run -
In [143]: A
Out[143]:
array([[1, 0, 0, 3, 4, 5],
[3, 0, 0, 9, 0, 0],
[5, 0, 0, 2, 2, 2],
[1, 0, 1, 5, 0, 0],
[5, 0, 1, 3, 0, 0],
[5, 1, 0, 0, 4, 0]])
In [144]: sortedA = A[A[:,0].argsort()]
In [145]: _,idx = np.unique(sortedA[:,0],return_index=True)
In [146]: np.split(sortedA[:,1:],idx[1:],axis=0)
Out[146]:
[array([[0, 0, 3, 4, 5],
[0, 1, 5, 0, 0]]), array([[0, 0, 9, 0, 0]]), array([[0, 0, 2, 2, 2],
[0, 1, 3, 0, 0],
[1, 0, 0, 4, 0]])]
Now, if you still want to have a dict-based
output, you could use the output from above, like so -
out_dict = {sortedA[:,0][idx[i]]:out[i] for i in range(len(idx))}
giving us -
In [153]: out
Out[153]:
[array([[0, 0, 3, 4, 5],
[0, 1, 5, 0, 0]]), array([[0, 0, 9, 0, 0]]), array([[0, 0, 2, 2, 2],
[0, 1, 3, 0, 0],
[1, 0, 0, 4, 0]])]
In [154]: {sortedA[:,0][idx[i]]:out[i] for i in range(len(idx))}
Out[154]:
{1: array([[0, 0, 3, 4, 5],
[0, 1, 5, 0, 0]]),
3: array([[0, 0, 9, 0, 0]]),
5: array([[0, 0, 2, 2, 2],
[0, 1, 3, 0, 0],
[1, 0, 0, 4, 0]])}