我做了嵌套串列
information = [['name', 'age', 'sex', 'height', 'weight'], ['sam', '17', 'm', 155, 55], [...]] to make table.
我想根據高度對資料進行排序。但是當我使用.sort()方法時,由于information[0],出現此錯誤訊息
"TypeError: '<' not supported between instances of 'float' and 'str'"
如何對除第一個元素以外的資料進行排序?


如您所見,我制作了表格以在 excel 檔案中查看。我想根據 G 列對元素進行排序。(這是電影資訊的代碼)但是當我嘗試使用sort()進行排序時,由于頂部元素是“???? ??”(str型別),因此無法進行排序。
uj5u.com熱心網友回復:
您可以sorted將第 4 個元素用作information不包含標題的切片上的鍵
information[1:] = sorted(information[1:], key=lambda x: x[3])
uj5u.com熱心網友回復:
如果可以接受使用熊貓庫,那么您可以將其創建為資料框。
import pandas as pd
df = pd.DataFrame(information)
# make the first row as column names
headers = df.iloc[0]
# create a updated dataframe with those new column names
updated_df = pd.DataFrame(df.values[1:], columns=headers)
# sort the values based on height
updated_df.sort_values('height', inplace=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365971.html
