Skip to content Skip to sidebar Skip to footer

Replace Element By Element Different Arrays

I have an array : a = np.array([1,2,3,4,5,6,7,8]) The array may be reshaped to a = np.array([[1,2,3,4],[5,6,7,8]]), whatever is more convenient. Now, I have an array : b = np.array

Solution 1:

For your current case, what you want is probably:

b, c = list(a.reshape(2, -1))

This isn't the cleanest, but it is a one-liner. Turn your 1D array into a 2D array with with the first dimension as 2 with reshape(2, -1), then list splits it along the first dimension so you can directly assign them to b, c

You can also do it with the specialty function numpy.split

b, c = np.split(a, 2)

EDIT: Based on accepted solution, vectorized way to do this is

b = a.reshape(b.shape)

Solution 2:

The following worked for me:

i = 0for arr in b:
    for idx, x inenumerate(arr):
        arr[idx] = a[i]
        print(arr[idx])
        i += 1

Output (arr[idx]): 1 2 3 4 5 6 7 8 If you type print(b) it'll output [[1 2 3 4] [5 6 7 8]]

Solution 3:

b = a[:len(a)//2] c = a[len(a)//2:]

Solution 4:

Well, I'm quite new to Python but this worked for me:

for i in range (0, len(a)//2):
        b[i] = a[i]
    for i in range (len(a)//2,len(a)):
        c[i-4] = a[i]

by printing the 3 arrays I have the following output:

[1 2 3 4 5 6 7 8]
[1 2 3 4]
[5 6 7 8]

But I would go for Daniel's solution (the split one): 1 liner, using numpy API, ...

Post a Comment for "Replace Element By Element Different Arrays"