如何根据 python 中的特定列(升序和降序)对 table 进行排序

how to sort a table based on a specific column (both scending and descending) in python

我需要你的帮助来根据特定列按升序和降序对 table 进行排序。

例如,我将这个 table 保存在名为“test.txt”的文件中

其中包含以下内容:

我用 prettytable:

将它转换为 csv table
from prettytable import from_csv
import csv, operator

with open('test.txt', 'r') as open_file:
    table_file = from_csv(open_file)
print(table_file)

the picture is attached as 1.png

然后我根据出生年份列进行排序:

print(table_file.get_string(sortby='BirthYear', sort_key=lambda row: row[0]))

the picture is attached as 2.png

如何对相同但降序排列? (基于任何列,而不仅仅是 BirthYear 列)。

如果你有不同的方法,知道学习它们会很棒。

提前致谢

如果要按降序对数据进行排序,请使用 sorted(),只需在 sorted 函数中添加 reverse=True,但它一次只能对一列进行排序。

from prettytable import from_csv
import csv, operator

with open('test.txt', 'r') as open_file:
  table_file = from_csv(open_file)
print(table_file)
 
srt =  sorted(data, key=operator.itemgetter(2), reverse=True) 
print(st)

或者您可以使用 pandas

from prettytable import from_csv
import csv, operator
import pandas as pd


with open('test.txt', 'r') as open_file:
    table_file = from_csv(open_file)
print(table_file)
srt = table_file.sort_values(["Age"], axis=0, ascending=[False], inplace=True)
print(st)


希望对你有所帮助。