python - 如何在 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 中生成上述结果?
解决方案
解决方案之一是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)
在转换为记录时跟踪您尝试排序的列的索引。
推荐阅读
- json - 使用 GoLang 的 API(几乎)RESTFul 变量响应
- android - 从 Firestore 中删除数据
- asp.net-mvc - JWT 令牌通常对使用跨域有效吗?
- javascript - 正确使用 wp.data.subscribe
- r - 在 r 中,如何根据文件名将 X 个固定宽度的平面文件读入 Y 个数据帧?
- c# - WCF 图像服务正在锁定文件
- graph - 我们可以同时过滤多个标签吗
- jquery - Jquery UI 日期选择器空白
- python - Python,参数解析。-opt1 -part-of-opt1 怎么样
? - mailchimp - 如何使用 Mailchimp API 获取用户所属的所有列表?