create new array from other arrays - python

I want to create a new array from three other arrays so that I want to create a 20x3 array (center_lab) from three 20x1 arrays (TT2r, TT2g, TT2b) so I would get the following:
center_lab = np.zeros([20,3])
center_lab[:,0] = TT2r
center_lab[:,1] = TT2g
center_lab[:,2] = TT2b
And I get the next error: could not broadcast input array from shape (21,1) into shape (21,)
Anyone knows how to fix this?

If im not mistaken your TT2r arrays have a shape of (21,1)
The part of center_lab you write into is only of shape (21,) since you index the last dimension (as opposed to slicing). If you also remove the last dimensions of your TTs it should fit.
center_lab = np.zeros([20,3])
center_lab[:,0] = TT2r[:,0]
center_lab[:,1] = TT2g[:,0]
center_lab[:,2] = TT2b[:,0]

create a 20x3 array (center_lab) from three 20x1 arrays
This sound like task for numpy.hstack, consider following simple example:
import numpy as np
arr1 = np.array([[1],[2],[3]])
arr2 = np.array([[4],[5],[6]])
arr3 = np.array([[7],[8],[9]])
arr = np.hstack([arr1,arr2,arr3])
print(arr)
output
[[1 4 7]
[2 5 8]
[3 6 9]]
Note: I used 3x1 array for sake of clarity. If you would need to stack vertically rather than horizontally as above see numpy.vstack.

Related

Reshaping array of shape x into an array of shape (x,y)

I am following a tutorial to implement the K-nearest Neighbor algorithm on a dataset.
I have an array of shape (6003,) and I want to do this:
data = data.reshape((data.shape[0], 3072))
However, I am getting this error:
cannot reshape array of size 6003 into shape (6003,3072)
Any help on this, please? Thanks!
when you reshape a numpy array the total number elements shouldn't change.
e.g. a =[2,3,4,5,1,7] if you want to reshape this to a 2Darray then the dimensions multiplied should be equal to the total number elements in the original array a.
this means you can reshape array a in to dimension of (1,6) (2,3),(6,1),(3,2).
the title of your question does give away the error by the way.
Reshaping array of shape (x,) into an array of shape (x,y)
is impossible because you are trying to add more elements into your original data.
an array of shape (x,) can only be reshaped into an array of shape (x/y,y)
I hope this helps.
You are trying to reshape into an incompatible shape. Now, what do I mean by that? Look at this example:
a = np.array([[1, 2, 3],
[4, 5, 6],
])
The shape of this array is:
a.shape
>> (2, 3)
Array a has 2 x 3 = 6 elements. Let's try to reshape it into a (2, 6) array
a.reshape(2, 6)
This raises
>> ValueError: cannot reshape array of size 6 into shape (2,6)
Notice that we were trying to make an array that has 2 x 3 = 6 elements into an array that would have 2 x 6 = 12 elements. But NumPy cannot add those extra elements into your original array and give that your desired shape. So it raises ValueError.
In your case, you are trying to make an array with 6003 elements into an array that will have 6003 x 3072 = 18441216 elements!

bootstrap numpy 2D array

I am trying to sample with replacement a base 2D numpy array with shape of (4,2) by rows, say 10 times. The final output should be a 3D numpy array.
Have tried the code below, it works. But is there a way to do it without the for loop?
base=np.array([[20,30],[50,60],[70,80],[10,30]])
print(np.shape(base))
nsample=10
tmp=np.zeros((np.shape(base)[0],np.shape(base)[1],10))
for i in range(nsample):
id_pick = np.random.choice(np.shape(base)[0], size=(np.shape(base)[0]))
print(id_pick)
boot1=base[id_pick,:]
tmp[:,:,i]=boot1
print(tmp)
Here's one vectorized approach -
m,n = base.shape
idx = np.random.randint(0,m,(m,nsample))
out = base[idx].swapaxes(1,2)
Basic idea is that we generate all the possible indices with np.random.randint as idx. That would an array of shape (m,nsample). We use this array to index into the input array along the first axis. Thus, it selects random rows off base. To get the final output with a shape (m,n,nsample), we need to swap last two axes.
You can use the stack function from numpy. Your code would then look like:
base=np.array([[20,30],[50,60],[70,80],[10,30]])
print(np.shape(base))
nsample=10
tmp = []
for i in range(nsample):
id_pick = np.random.choice(np.shape(base)[0], size=(np.shape(base)[0]))
print(id_pick)
boot1=base[id_pick,:]
tmp.append(boot1)
tmp = np.stack(tmp, axis=-1)
print(tmp)
Based on #Divakar 's answer, if you already know the shape of this 2D-array, you can treat it as an (8,) 1D array while bootstrapping, and then reshape it:
m, n = base.shape
flatbase = np.reshape(base, (m*n,))
idxs = np.random.choice(range(8), (numReps, m*n))
bootflats = flatbase[idx]
boots = np.reshape(flatbase, (numReps, m, n))

How To ReShape a Numpy Array in Python

I have a numpy array of images with the shape of (5879,). Inside every index of the numpy array, I have the Pixels of the image with a shape of (640,640,3).
I want to reshape the complete array in such a way that the shape of the numpy array becomes (5879,640,640,3).
please check, whether below code works for you or not
import numpy as np
b = np.array([5879])
b.shape
output (1,)
a = np.array([[640],[640],[3]])
a = a.reshape((a.shape[0], 1))
a.shape
output (3, 1)
c = np.concatenate((a,b[:,None]),axis=0)
c.shape
Output:
(4, 1)
np.concatenate((a,b[:,None]),axis=0)
output
array([[ 640],
[ 640],
[ 3],
[5879]])
You want to stack your images along the first axis, into a 4D array. However, your images are all 3D.
So, first you need to add a leading singleton dimension to all images, and then to concatenate them along this axis:
imgs = [i_[None, ...] for i_ in orig_images] # add singleton dim to all images
x = np.concatenate(imgs, axis=0) # stack along the first axis
Edit:
Based on Mad Phyiscist's comment, it seems like using np.stack is more appropriate here: np.stack takes care of adding the leading singleton dimension for you:
x = np.stack(orig_images, axis=0)

Are the dimensions of arrays max 2 that be created with np.arange?

I'm new in NumPy. While i was reading the NumPy User Guide and making examples , i saw an example that made me to ask a question.
For example Python gave the below results:
>>> import numpy as np
>>> a = np.arange(6)
>>> a.ndim
1
>>> b = np.arange(6).reshape(2,3)
>>> b.ndim
2
>>> c = np.arange(6).reshape(3,2)
>>> c.ndim
2
I expected that c.ndim would given 3 rather than 2. So my question is, are the max dimension sizes of arrays are 2 when these arrays are created with np.arange() function?
What you are actually doing is first creating a 1D array with arange then reshape it.
a = np.arange(20) # of dimension 1
a = a.reshape(4,5)
print(a.ndim) # returns 2 because the array became a 2D 4x5
a = a.reshape(2,5,2)
print(a.ndim) # returns 3 because the array becomes a 3D 2x5x2
to summarize, you are forcing a reshape of a 1D np.array to a 2D using the reshape method, add more arguments to access more dimensions.

Convert a 1D array to a 2D array in numpy

I want to convert a 1-dimensional array into a 2-dimensional array by specifying the number of columns in the 2D array. Something that would work like this:
> import numpy as np
> A = np.array([1,2,3,4,5,6])
> B = vec2matrix(A,ncol=2)
> B
array([[1, 2],
[3, 4],
[5, 6]])
Does numpy have a function that works like my made-up function "vec2matrix"? (I understand that you can index a 1D array like a 2D array, but that isn't an option in the code I have - I need to make this conversion.)
You want to reshape the array.
B = np.reshape(A, (-1, 2))
where -1 infers the size of the new dimension from the size of the input array.
You have two options:
If you no longer want the original shape, the easiest is just to assign a new shape to the array
a.shape = (a.size//ncols, ncols)
You can switch the a.size//ncols by -1 to compute the proper shape automatically. Make sure that a.shape[0]*a.shape[1]=a.size, else you'll run into some problem.
You can get a new array with the np.reshape function, that works mostly like the version presented above
new = np.reshape(a, (-1, ncols))
When it's possible, new will be just a view of the initial array a, meaning that the data are shared. In some cases, though, new array will be acopy instead. Note that np.reshape also accepts an optional keyword order that lets you switch from row-major C order to column-major Fortran order. np.reshape is the function version of the a.reshape method.
If you can't respect the requirement a.shape[0]*a.shape[1]=a.size, you're stuck with having to create a new array. You can use the np.resize function and mixing it with np.reshape, such as
>>> a =np.arange(9)
>>> np.resize(a, 10).reshape(5,2)
Try something like:
B = np.reshape(A,(-1,ncols))
You'll need to make sure that you can divide the number of elements in your array by ncols though. You can also play with the order in which the numbers are pulled into B using the order keyword.
If your sole purpose is to convert a 1d array X to a 2d array just do:
X = np.reshape(X,(1, X.size))
convert a 1-dimensional array into a 2-dimensional array by adding new axis.
a=np.array([10,20,30,40,50,60])
b=a[:,np.newaxis]--it will convert it to two dimension.
There is a simple way as well, we can use the reshape function in a different way:
A_reshape = A.reshape(No_of_rows, No_of_columns)
You can useflatten() from the numpy package.
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")
Output:
original array: [[1 2]
[3 4]
[5 6]]
flattened array = [1 2 3 4 5 6]
some_array.shape = (1,)+some_array.shape
or get a new one
another_array = numpy.reshape(some_array, (1,)+some_array.shape)
This will make dimensions +1, equals to adding a bracket on the outermost
Change 1D array into 2D array without using Numpy.
l = [i for i in range(1,21)]
part = 3
new = []
start, end = 0, part
while end <= len(l):
temp = []
for i in range(start, end):
temp.append(l[i])
new.append(temp)
start += part
end += part
print("new values: ", new)
# for uneven cases
temp = []
while start < len(l):
temp.append(l[start])
start += 1
new.append(temp)
print("new values for uneven cases: ", new)
import numpy as np
array = np.arange(8)
print("Original array : \n", array)
array = np.arange(8).reshape(2, 4)
print("New array : \n", array)

Categories

Resources