首页 > 解决方案 > 如何在 Python 中按项目对 List 的值进行排序?

问题描述

例如,我有如下数据框程序:

lst3 = [
        ['it store', ['asus', 'acer', 'hp', 'dell'], [50000, 30000, 20000, 10000]],
        ['mz store', ['acer', 'dell'], [60000, 75000]],
        ['bm shop', ['hp', 'acer', 'asus'], [45000, 15000, 30000]]
       ]

df3 = pd.DataFrame(lst3, columns =['store_name', 'item', 'price'], dtype = float) 
print(df3)

结果是:

  store_name                    item                         price
0   it store  [asus, acer, hp, dell]  [50000, 30000, 20000, 10000]
1   mz store            [acer, dell]                [60000, 75000]
2    bm shop        [hp, acer, asus]         [45000, 15000, 30000]

“项目”和“价格”列的类型是列表。

因此,例如,我想按项目“acer”的最低价格对数据框进行排序。预期结果是:

  store_name                    item                         price
2    bm shop        [hp, acer, asus]         [45000, 15000, 30000]
0   it store  [asus, acer, hp, dell]  [50000, 30000, 20000, 10000]
1   mz store            [acer, dell]                [60000, 75000]

[编辑:附加] 而且,如果按项目 'hp' 的最低价格对数据框进行排序,则预期结果为:

  store_name                    item                         price
0   it store  [asus, acer, hp, dell]  [50000, 30000, 20000, 10000]
2    bm shop        [hp, acer, asus]         [45000, 15000, 30000]

你能帮我吗,程序脚本如何在 Python 中生成上述结果?

标签: pythonpandasdataframe

解决方案


解决方案之一是DataFrame使用方法将其转换为记录to_records()

使用 python 的内置sorted()函数对其进行排序。

然后将其转换回DataFrame使用from_records().

对于您当前DataFrame在列表中按最低价格排序,您可以执行以下操作。

sorted_records = sorted(df3.to_records(), key=lambda x: min(x[3]))
df3 = pd.DataFrame.from_records(sorted_records)

在转换为记录时跟踪您尝试排序的列的索引。

pd.DataFrame.to_records()

pd.DataFrame.from_records()


推荐阅读