pandas - 用熊猫创建嵌套对象
问题描述
input_data = {
'url1': ['https://my-website.com/product1', 'https://my-website.com/product1', 'https://my-website.com/product2', 'https://my-website.com/product2'],
'url2': ['https://not-my-website.com/product1', 'https://not-my-website.com/product1', 'https://not-my-website.com/product2', 'https://not-my-website.com/product2'],
'size': ['S', 'L', 'S', 'L'],
'used_price': [100, 110, 210, 220],
'new_price': [1000, 1100, 2100, 2200],
}
input_df = pd.DataFrame(data=input_data)
output_data = {
'url1': ['https://my-website.com/product1', 'https://my-website.com/product2'],
'url2': ['https://not-my-website.com/product1', 'https://not-my-website.com/product2'],
'target': [
{
'S': {'used_price': 100, 'new_price': 1000},
'L': {'used_price': 120, 'new_price': 1200}
},
{
'S': {'used_price': 200, 'new_price': 2000},
'L': {'used_price': 220, 'new_price': 2200}
}
]
}
output_df = pd.DataFrame(data=output_data)
解决方案
您可以使用groupby
和apply
:
(input_df.groupby(['url1', 'url2'])[['size', 'used_price', 'new_price']]
.apply(lambda d: d.set_index('size').T.to_dict())
.rename('target')
.reset_index()
)
输出:
url1 url2 target
0 https://my-website.com/product1 https://not-my-website.com/product1 {'S': {'used_price': 100, 'new_price': 1000}, 'L': {'used_price': 110, 'new_price': 1100}}
1 https://my-website.com/product2 https://not-my-website.com/product2 {'S': {'used_price': 210, 'new_price': 2100}, 'L': {'used_price': 220, 'new_price': 2200}}
推荐阅读
- javascript - 当页面上显示的数据至关重要时,页面会不断刷新
- android - 如何在一定距离的路线周围区域上设置多边形(在 HereMaps 中)
- python - 如何将 pyqt4 中创建的列表中的项目按字母顺序返回
- delphi - Delphi Can't load package 找不到指定的模块
- scala - How to disable -Xfatal-warnings in Scala project?
- r - 求解 polynom::polynomial 时 R 中的 setdiff 问题
- python - 如何在 Python 中编码为德语?
- javascript - member.ban 不是函数
- vb.net - 为什么Visual Studio在声明字符串数组列表时会抛出异常
- python - pandas:选择所选行的相邻行