前一天我们学会了对资料进行简单的map处理之後,今天来聊一下排序
不论是进行人工的检视或是後续分析的需求,排序是一个我们会很常到的工具
在python中最简单的排序可以透过呼叫sorted(要排序的list)
来进行
A = [1,3,5,1,2]
sorted(A)
输出:
[1, 1, 2, 3, 5]
A = [1,3,5,1,2]
sorted(A,reverse=True)
输出:
[5, 3, 2, 1, 1]
如果传入的资料是tuple
类型的,就会先按照第1个元素比较大小进行排序,如果相同的时候则会比较第二个,更多个元素的时候以此类推
B = [("Alice",100), ("Bob", 97), ("Carol", 97), ("Bob", 95) ]
sorted(B)
输出:
[('Alice', 100), ('Bob', 95), ('Bob', 97), ('Carol', 97)]
因此这边我们可以发现这笔资料先按照了人名排序,而相同是Bob的地方则是再从分数小的排到大
这边使用lambda
函式来取出每个元素的第[1]
个元素来比较(100,97,97,95)
# 指定排序元素
B = [("Alice",100), ("Bob", 97), ("Carol", 97), ("Bob", 95) ]
sorted(B,key=lambda x: x[1]) # x为list内每个元素,依照x[1]的元素进行比较
输出:
[('Bob', 95), ('Bob', 97), ('Carol', 97), ('Alice', 100)]
# 指定排序规则
C = ["Alice", "Bob", "Bob", "Bob", "Carol"]
sorted(C,key=len) # 依照长度进行排序
输出:
['Bob', 'Bob', 'Bob', 'Alice', 'Carol']
.sort()
和sorted
差在哪里?A = [1,3,5,1,2]
B = sorted(A)
print("A:", A)
print("B:", B)
A: [1, 3, 5, 1, 2]
B: [1, 1, 2, 3, 5]
A = [1,3,5,1,2]
B = A.sort()
print("A:", A)
print("B:", B)
A: [1, 1, 2, 3, 5]
B: None
我们这边先建立一个字串list作为测试
A = ["file"+str(x) for x in range(15)]
A
['file0',
'file1',
'file2',
'file3',
'file4',
'file5',
'file6',
'file7',
'file8',
'file9',
'file10',
'file11',
'file12',
'file13',
'file14']
sorted(A)
['file0',
'file1',
'file10',
'file11',
'file12',
'file13',
'file14',
'file2',
'file3',
'file4',
'file5',
'file6',
'file7',
'file8',
'file9']
我们发现这边它先排了1开头的10, 11, ..., 14,才排2,3,4...
这似乎和我们想要达成的依照数字排序有点不同
由於natsort
不是内建的package,我们需要先进行安装
这边可以使用pip来进行安装
pip install natsort
from natsort import natsorted
natsorted(A)
['file0',
'file1',
'file2',
'file3',
'file4',
'file5',
'file6',
'file7',
'file8',
'file9',
'file10',
'file11',
'file12',
'file13',
'file14']
刚好最近刚爬完学校公布的成绩分布,就拿这个当作范例好了
import pandas as pd
df = pd.read_excel("GPA.xlsx")
df
sort_values
df.sort_values("平均值")
by=["栏位1","栏位2"]
df.sort_values(by= ["标准差", "平均值"])
ascending=["栏位1","栏位2"]
df.sort_values(by= ["标准差", "平均值"], ascending=[True, False])
>>: Swift纯Code之旅 Day17. 「复习 - 新增页面、TableView、TableViewCell」
运算子(Operator) 在程序码中代表运算的符号,参与运算的数值或变数称为运算元(Operand...
第一天来发表一下30days将发布的内容, 然後我们来进行Mac与Windows的Java环境与开发...
The Abstract Factory pattern provides an interface...
进入十月~我开始临时抱佛脚 除了维持写文以来的努力喝水和少量运动 我也开始去做一些脸部保养课程~ B...
昨天把骰子的程序逻辑都先完成了,这次我们将这个逻辑应用在 Android Studio 里。但我们今...