python - Python:如何将具有相同变量类型的多个列表合并到一个列表列表中?
问题描述
如何将三个列表列表组合成一个列表,以便第二级列表的第一个字符串出现在新列表列表的第一行和相应的第二个字符串中 - 在下一行(每个列表一行)?
假设有三个列表,如下所示:
[['item_1', 'price_100'], ['item_2', 'price_200']] #from shop_a
[['item_1', 'price_120'], ['item_2', 'price_180']] #from shop_b
[['item_2', 'price_80'], ['item_3', 'price_220']] #from shop_c
我想将它们合并到一个列表中,如下所示:
[['item_name', 'shop_a', 'shop_b', 'shop_c'], #should become the header of the DataFrame
['item_1', 'price_100', 'price_120', ''], #should become the 1st row of the DF
['item_2', 'price_200', 'price_180', 'price_80'], #should become the 2nd row of the DF
['item_3', '', '', 'price_220']] #should become the 3rd row of the DF
这个想法是在每一行中获取同一商品的所有价格,以便从列表构建的 DataFrame 将代表一个方便的矩阵来比较不同商店的价格。
这该怎么做?我将不胜感激任何建议...
PS:请考虑行的长度不相等(第三个列表与前两个不同)。
解决方案
您可以dictionary
使用项目名称作为键将它们存储在 a 中,然后按字母顺序对它们进行排序并创建 a df
,例如:
import pandas as pd
a = [['item_1', 'price_100'], ['item_2', 'price_200']] #from shop_a
b = [['item_1', 'price_120'], ['item_2', 'price_180']] #from shop_b
c = [['item_2', 'price_80'], ['item_3', 'price_220']] #from shop_c
data = {}
for item in a + b + c:
item_name = item[0]
item_price = item[1]
item_data = data.get(item_name, ['', '', ''])
item_data.append(item_price)
item_data.pop(0)
data[item_name] = item_data
sorted_rows = sorted([
[item_data[0]]+item_data[1] for item_data in data.items()
], key=lambda item: item[0])
df = pd.DataFrame(sorted_rows, columns=['item_name', 'shop_a', 'shop_b', 'shop_c'])
print(df)
>>>
item_name shop_a shop_b shop_c
0 item_1 price_100 price_120
1 item_2 price_200 price_180 price_80
2 item_3 price_220
推荐阅读
- docker - Docker Swarm:如何修复 swarm 网络名称
- javascript - 仅当窗口宽度大于 1024px 时才执行函数,实时检查宽度
- javascript - 为每个 React 组件指定不同的 momentJS 语言环境
- snowflake-cloud-data-platform - 错误:将数据从 Oracle 插入到 Snowflake 时超过 255 个字符的最大长度限制?
- swift - 如何:检测可观察对象是否在 RxSwift 中的特定时间未发出任何事件
- symfony4 - 您请求了一个不存在的服务“fos_user.manager”
- ios - 我在哪里可以找到 iPhone 模拟器上的 MyDocuments 文件夹?
- python - 我的 while 循环只在第二次而不是第一次工作
- javascript - AJAX 仅发布第一个表单
- maven - Maven测试不显示测试结果