Sorting a Python list by two fields
like this:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
Sort a list by multiple attributes?
A key can be a function that returns a tuple:
s = sorted(s, key = lambda x: (x[1], x[2]))
Or you can achieve the same using itemgetter
(which is faster and avoids a Python function call):
import operator
s = sorted(s, key = operator.itemgetter(1, 2))
And notice that here you can use sort
instead of using sorted
and then reassigning:
s.sort(key = operator.itemgetter(1, 2))
Python - order list of lists by multiple column indexes
Since it does not matter whether you sort by the third column as well, or not, you can use plain sort
here, and get the same result:
>>> sorted(a)
[['a', 4, 'dd'], ['a', 6, 'aa'], ['c', 1, 'cc'], ['d', 2, 'ee'], ['d', 7, 'bb']]
This is because lists are compared left to right and sorted in lexicographical order.
If you did want to order by arbitrary column order, you should use operator.itemgetter
, which is faster than using a lambda
function for the key
.
>>> import operator
>>> sorted(a, key=operator.itemgetter(1, 0)) # order by column 1 first, then 0.
[['c', 1, 'cc'], ['d', 2, 'ee'], ['a', 4, 'dd'], ['a', 6, 'aa'], ['d', 7, 'bb']]
Sort by two columns at once
I think you need assign output to new DataFrame
, parameter ascending
can be omit, because ascending=True
is default value in DataFrame.sort_values
:
data = data.sort_values(by=['A','B'])
print (data)
A B C
0 1 4 string1
2 1 13 string3
1 2 11 string2
3 2 43 string4
How to sort two columns at once using sorted()
You can sort by two aspects by having the key
callable return a tuple.
I'm assuming that the second column is a string convertable to an integer:
sortedColumn = sorted(csv_opener, key=lambda row: (row[0], -int(row[1])))
By returning negative values from row[1]
you can sort from highest-to-lowest, while the main sort is done or row[0]
in alphabetical order.
So for the sample rows:
Alpha, 10
Beta, 30
Alpha, 42
Gamma, 81
Beta, 10
the sorted output gives you:
Alpha, 42
Alpha, 10
Beta, 30
Beta, 10
Gamma, 81
sorting first alphabetically on the first column, and then for equal values in the first column, the rows are sorted in descending order on the second column.
Python sorting based on two fields of the file data
You'll need to cast your strings to a numeric type to avoid a lexicographical sort and then invert the order of the second sort criterion to make it descending:
s = sorted(mylist,key=lambda x: (x[0], -float(x[2])))
# ^ invert sort order
[['K1', '6.48153375', '1.4176140292'],
['K1', '6.66228125', '1.0444456163'],
['K1', '8.025495625', '0.7561548244'],
['K1', '8.6394253125', '0.6690271589'],
['K1', '4.1458078125', '0.5129700421'],
['k2', '6.319044375', '0.6469451082'],
['k2', '9.5360690625', '0.5481493305'],
['k3', '9.2603346875', '0.4639390435'],
['k4', '10.6868384375', '1.1287761798'],
['k5', '7.2702040625', '0.6632701035'],
['k6', '7.73398625', '1.017231759'],
['k7', '9.8022878125', '0.562983695'],
['k8', '5.44912125', '0.8532092538'],
['k9', '7.5859665625', '1.276779643']]
Set Ascending Descending for each column when sorting by multiple columns
From the docs:
reverse is a boolean value. If set to
True
, then the list elements are sorted as if each comparison were reversed.
So what you want instead is something like:
d.sort(key=lambda x: (x[0], -x[1]))
If x[1]
is not a number, try:
d.sort(key=lambda x: x[1], reverse=True)
d.sort(key=lambda x: x[0])
Sort a nested list by two elements
>>> sorted(l, key=lambda x: (-int(x[1]), x[0]))
[['Anthony', '10'], ['Ben', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']]
Basically, by changing the sign of the score part of the key, the sort keys will be:
(-10, 'Anthony'),
(-10, 'Ben'),
(-7, 'Adam'),
(-6, 'Joe'),
(-4, 'Harry')
And so, with (a, b) < (c, d) <=> (a < c) or (a == c and b < d)
, you end up with your desired sorting order.
how to sort by 2 fields using lambda in python
You can create a tuple containing the items of priority in the sort key
:
student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ('mike', 'A', 12)]
new_tuples = sorted(student_tuples, key=lambda data:(data[-1], data[1]))
Output:
[('dave', 'B', 10), ('mike', 'A', 12), ('jane', 'B', 12), ('john', 'A', 15)]
Related Topics
How to Filter Only Printable Characters in a File on Bash (Linux) or Python
How to Open Process Again in Linux Terminal
Bring the Current Python Program to Background
Why Aren't Python Nested Functions Called Closures
Integer Division in Python 2 and Python 3
Pg_Config Executable Not Found
What Does the _File_ Variable Mean/Do
Http Requests and JSON Parsing in Python
Find the Column Name Which Has the Maximum Value for Each Row
Problem Running Python from Crontab - "Invalid Python Installation"
How to Install Python 3.6.5 on My Ubuntu 19.10 That Already Contains Python 3.7.5
Gdb Pretty Printing with Python a Recursive Structure
How to Emulate a Do-While Loop
Iterating on a File Doesn't Work the Second Time
How to Return Dictionary Keys as a List in Python