How does your "2D array" look like?

For example:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4,  3,  1, 2], 
 [15, 8,  9, 6], 
 [12, 18, 6, 3]]

But I guess you want something like this:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a = zip(*a)
>>> a.sort(key=lambda x: x[1])
>>> a
[(6,  1,  9), 
 (3,  2,  6), 
 (18, 3,  8), 
 (12, 4, 15)]
>>> a = zip(*a)
>>> a
[(6, 3, 18, 12), 
 (1, 2,  3,  4), 
 (9, 6,  8, 15)
]
Answer from Messa on Stack Overflow
Top answer
1 of 6
46

How does your "2D array" look like?

For example:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4,  3,  1, 2], 
 [15, 8,  9, 6], 
 [12, 18, 6, 3]]

But I guess you want something like this:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a = zip(*a)
>>> a.sort(key=lambda x: x[1])
>>> a
[(6,  1,  9), 
 (3,  2,  6), 
 (18, 3,  8), 
 (12, 4, 15)]
>>> a = zip(*a)
>>> a
[(6, 3, 18, 12), 
 (1, 2,  3,  4), 
 (9, 6,  8, 15)
]
2 of 6
23

Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module array. There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", right?-)

So I'll assume that by "2d array" you mean a list of lists, such as:

lol = [ range(10), range(2, 12), range(5, 15) ]

or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item lol[1]. Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.

So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:

indices = range(10)
indices.sort(key = lol[1].__getitem__)
for i, sublist in enumerate(lol):
  lol[i] = [sublist[j] for j in indices]

The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.

If you actually have a different problem, there will of course be different solutions;-).

🌐
Note.nkmk.me
note.nkmk.me › home › python
Sort a 2D List in Python | note.nkmk.me
July 27, 2023 - The operator module in Python (itemgetter, attrgetter, methodcaller) To sort according to a specific row, transpose the array, apply the sorting operation as described above, and then transpose the array back.
Discussions

How would you sort a 2D list by row based on the first column using a separate list as a key
If you want to sort it by month, why not use a dictionary of lists, such that dict['Nov'] = [0.0, 0.0, 0.09, etc.]? More on reddit.com
🌐 r/learnpython
3
1
November 22, 2022
python - How to sort multidimensional array by column? - Stack Overflow
1 How to sort a multidimensional list to alphabetical order based on its first row letters in python ... 3 how to sort a multidimensional array with one column in ascending order and another column in descending order? More on stackoverflow.com
🌐 stackoverflow.com
Sorting 2d Array
Posted by u/PhantomWizard2099 - 2 votes and 14 comments More on reddit.com
🌐 r/learnpython
14
2
June 28, 2023
Sorting 2d array by rows in python - Stack Overflow
I would like to rearrange the rows in a python numpy array according to descending order of the first column. For Example, ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. More on stackoverflow.com
🌐 stackoverflow.com
🌐
thisPointer
thispointer.com › home › numpy › sorting 2d numpy array by column or row in python
Sorting 2D Numpy Array by column or row in Python - thisPointer
July 5, 2019 - <New positioning of columns> = arr[rowindex].argsort() Then change the positioning of columns to make this 2d array sorted by row.
🌐
Like Geeks
likegeeks.com › home › python › numpy › sorting numpy arrays: a comprehensive guide
Sorting NumPy Arrays: A Comprehensive Guide
Learn how to sort Python NumPy arrays in ascending or descending order, 2D, 3D arrays, using np.sort() method, sort 2D and 3D arrays, and more.
🌐
Reddit
reddit.com › r/learnpython › how would you sort a 2d list by row based on the first column using a separate list as a key
r/learnpython on Reddit: How would you sort a 2D list by row based on the first column using a separate list as a key
November 22, 2022 -

so i have a data set of rain data over the course of a year where it ends up being formatted into something like this except its a lot longer

[['Nov', 0.0], ['Nov', 0.0], ['Nov', 0.09],['Feb', 0.0], ['Feb', 0.0], ['Feb', 0.09],['Oct', 0.56], ['Oct', 0.0], ['Oct', 0.03], ['Oct', 0.62]]

now I figured I would need another list to function as a lookup to help sort this data by month according to calendar order so I made one

month_lookup = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

but now I am a tad confused about how I would go about using something like the sorted() function to use the lookup as the way to sort the 2D list above

🌐
Delft Stack
delftstack.com › home › howto › python › sort 2d array python
How to Sort 2D Array in Python | Delft Stack
February 2, 2024 - from operator import itemgetter lst = [ ("john", "C", 15), ("jane", "A", 12), ("dave", "D", 10), ] sorted_lst = sorted(lst, key=itemgetter(1)) print(sorted_lst) ... Enjoying our tutorials?
Find elsewhere
🌐
ProjectPro
projectpro.io › recipes › sort-2d-array-by-column-numpy
How to sort a 2D array by a column in numpy? -
June 22, 2022 - MACHINE LEARNING RECIPES DATA CLEANING PYTHON DATA MUNGING PANDAS CHEATSHEET ALL TAGS · How to sort a 2D array by a column. yes we can do this and for that we have to use the "sort" function available in the numpy library.
🌐
Reddit
reddit.com › r/learnpython › sorting 2d array
r/learnpython on Reddit: Sorting 2d Array
June 28, 2023 - Step 1. Go through the 2d array. Place each entry into a single array. Step 2. Sort the single array. Step 3. Put the results of the sorted array into a new array, grouping them by two entries.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 370908 › sorting-a-2d-array
python - Sorting a 2D Array | DaniWeb
July 4, 2011 - # Sample data rows = [ [2, 190], [7, 101], [1, 100], [3, 100], [9, 100], ] # 1) Sort rows by first column (ascending) rows_by_col0 = sorted(rows, key=lambda r: r[0]) # 2) Sort rows by second column, then first column to break ties ...
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.sort.html
numpy.ndarray.sort — NumPy v2.5 Manual
Sort an array in-place. Refer to numpy.sort for full documentation · Axis along which to sort. Default is -1, which means sort along the last axis
🌐
Sharp Sight
sharpsight.ai › blog › numpy-sort
A quick guide to NumPy sort - Sharp Sight
February 6, 2024 - As you can see, the code -np.sort(-array_2d, axis = 0) produces an output array where the columns have been sorted in descending order, from the top of the column to the bottom. You can do the same thing to sort the rows by using axis = 1.
🌐
Codefinity
codefinity.com › courses › v2 › 4f4826d5-e2f8-4ffd-9fd0-6f513353d70a › a4da9564-36a0-4109-b920-88fc7b89ddbb › e919a538-f041-447b-8082-e453a3c2aa5b
Learn Sorting 2D Arrays | Commonly used NumPy Functions
As you can see, simply passing our 2D array to the sort() function sorts each 1D array along the axis 1 (which is the default option in a 2D array).
🌐
Script Everything
scripteverything.com › posts › how to sort 2d array in python: 1 line of code without numpy
How To Sort 2D Array In Python: 1 Line Of Code Without Numpy | Script Everything
July 29, 2021 - To sort a two-dimensional list using multiple columns and different sorting methods (eg. descending order for one, ascending order for another) in Python, without using any imported libraries, use the built-in sort() list method and sorted() function. By using the built-in sort list method ...
🌐
Codehamster
codehamster.com › codehamster | "everything should be made as simple as possible, but not simpler." -- albert einstein › codes › python › sort 2d array in python
sort 2d array in python - Codehamster
October 12, 2024 - There are many ways to sort a 2d arrays. In general, you can use the sorted(), np.array.sort(),... But you should also understand what is meaning of list1.sort(list2) ravel() vs. flatten() what return the key function back in sorted() what will be returned by np.lexsort(), np.argsort()