Reputation: 37
I have multiple arrays in which they "switch" values unexpectedly.
I have three numpy arrays that should be:
a=[1 2 3 4], b=[7 8 9 10], c=[11 12 13 14]
However, they are in the current format:
a=[1 2 9 10], b=[7 8 13 14], c=[11 12 3 4]
What code can write such that the arrays are in the order as above? Please note that I do not know the indices at which the "switch" occurs at.
Upvotes: 1
Views: 725
Reputation: 82765
Using numpy.concatenate()
and numpy.reshape()
Ex:
import numpy as np
a=np.array([1, 2, 9, 10])
b=np.array([7, 8, 13, 14])
c=np.array([11, 12, 3, 4])
main = np.concatenate((a, b, c))
main.sort()
a, b, c = main.reshape(3, 4)
print(a) #[1 2 3 4]
print(b) #[ 7 8 9 10]
print(c) #[11 12 13 14]
Upvotes: 2
Reputation: 39052
Since you need ordered values, you can first concatenate
the three arrays and sort
and then reshape
to get individual arrays
a=np.array([1, 2, 9, 10])
b=np.array([7, 8, 13, 14])
c=np.array([11, 12, 3, 4])
a, b, c = np.sort(np.concatenate((a,b,c))).reshape((3, 4))
a, b, c
# (array([1, 2, 3, 4]), array([ 7, 8, 9, 10]), array([11, 12, 13, 14]))
Upvotes: 2
Reputation: 23521
You can achieve this by merge all your arrays then be resizing the output:
import numpy
a = numpy.array([1,2,9,10])
b = numpy.array([7,8,13,14])
c = numpy.array([11,12,3,4])
# merge, sort and reshape your arrays
d = numpy.sort(numpy.concatenate((a, b, c))).reshape(3,4)
# asssign them back
a,b,c = d
print(a)
print(b)
print(c)
Upvotes: 1
Reputation: 20490
You can append all three lists together, sort them, and then resplit the list into 3 parts again using list comprehension
a=[1, 2, 9 ,10]
b=[7 ,8, 13, 14]
c=[11 ,12, 3, 4]
#Append elements and sort them together
li = sorted(a+b+c)
#Resplit the list into 3 parts
a, b, c = [li[idx:idx+4] for idx in range(0,len(li),4)]
print(a,b,c)
The output will be
[1, 2, 3, 4] [7, 8, 9, 10] [11, 12, 13, 14]
Upvotes: 2
Reputation: 1662
You could create a list containing all elements, sort this list and split it up again:
>>> a = [1, 2, 9, 10]
>>> b = [7, 8, 13, 14]
>>> c = [11, 12, 3, 4]
>>> s = sorted(a + b + c)
>>> a, b, c = s[:4], s[4:8], s[8:]
>>> a, b, c
([1, 2, 3, 4], [7, 8, 9, 10], [11, 12, 13, 14])
Upvotes: 1