另一种方法是使用numpy
'argsort()
函数。它按照排序后的顺序返回索引。
import numpy as np
table = [['255.255.255.255', '58267', '233', 'ESTABLISHED'], ['255.132.0.0', '38367', '273', 'CLOSED']]
sorted_indexes = np.argsort([row[-1] for row in table])
sorted_table = np.array(table)[sorted_indexes]
# as list (and not numpy array):
sorted_table.tolist()
# [['255.132.0.0', '38367', '273', 'CLOSED'],
# ['255.255.255.255', '58267', '233', 'ESTABLISHED']]
但好处np.argsort()
是它也适用于 Pandas 数据框:
import pandas as pd
df = pd.DataFrame(table)
sorted_indexes = np.argsort(df.iloc[:, -1])
sorted_df = df.iloc[sorted_indexes, :]
sorted_df
# 0 1 2 3
# 1 255.132.0.0 38367 273 CLOSED
# 0 255.255.255.255 58267 233 ESTABLISHED
# you can get numpy arrays by `.values`
# and from numpy array to normal lists by `.tolist()
# so:
sorted_df.values.tolist()
# [['255.132.0.0', '38367', '273', 'CLOSED'],
# ['255.255.255.255', '58267', '233', 'ESTABLISHED']]
但是 Pandas 当然有内置排序:
df.sort_values(by=[3])
并且您可以给出by
几个列名或列索引,它们确定排序的优先列值。使用.values.tolist()
您可以将数据框重新转换回简单列表。