I have an array [0,1,1,2,0,2]. I wish to make a ndarray:
array([[[1],
[0],
[0],
[0],
[1],
[0]],
[[0],
[1],
[1],
[0],
[0],
[0]],
[[0],
[0],
[0],
[1],
[0],
[1]]])
Is there a way to do with just numpy functions without using any loops or list comprehension? Thanks.
Currently, what I did was
a = np.array([0,1,1,2,0,2])
len_a = len(a)
unique_count_a = len(np.unique(a))
t = np.ndarray(shape = (unique_count_a,len_a,1),dtype = int,buffer = np.zeros(len_a * unique_count_a))
for i in range(unique_count_a):
for j in range(len_a):
if i == j:
t[i,j]=1
CodePudding user response:
You can try the following:
import numpy as np
a = [0,1,1,2,0,2]
out = np.zeros((max(a) 1, len(a), 1), dtype=int)
out[a, np.r_[:len(a)]] = 1
print(out)
It gives:
[[[1]
[0]
[0]
[0]
[1]
[0]]
[[0]
[1]
[1]
[0]
[0]
[0]]
[[0]
[0]
[0]
[1]
[0]
[1]]]
CodePudding user response:
We don't normally use ndarray
, unless constructing an special array from a preexisting buffer. All you need is:
t1 = np.zeros((unique_count_a,len_a,1),dtype = int)
Since that last size 1 dimension makes the display longer, I'll omit that
In [450]: t[:,:,0]
Out[450]:
array([[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]])
That's not what you display.
But we can easily generate it with:
In [451]: (np.arange(unique_count_a)[:,None]==np.arange(len_a))
Out[451]:
array([[ True, False, False, False, False, False],
[False, True, False, False, False, False],
[False, False, True, False, False, False]])
In [452]: (np.arange(unique_count_a)[:,None]==np.arange(len_a)).astype(int)
Out[452]:
array([[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]])
What I think you want is:
In [454]: u = np.unique(a)
In [457]: for i in range(t1.shape[0]):
...: for j in range(t1.shape[1]):
...: if u[i]==a[j]:
...: t1[i,j] = 1
...:
In [458]: t1
Out[458]:
array([[1, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1]])
Let's just compare the unique values against a
:
In [460]: u[:,None]==a
Out[460]:
array([[ True, False, False, False, True, False],
[False, True, True, False, False, False],
[False, False, False, True, False, True]])
In [461]: (u[:,None]==a).astype(int)
Out[461]:
array([[1, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1]])
We could easily reshape it to (3,6,1).