python - 使用两列中的元组样式键将数据框转换为嵌套自定义字典的最 Pythonic 方法
问题描述
我有以下数据框:
import pandas as pd
df = pd.DataFrame({
"color": ["blue", "blue", "blue", "blue", "green", "green", "green", "green"],
"object": ["hat", "hat", "coat", "coat", "hat", "hat", "coat", "coat"],
"group": [1, 2, 1, 2, 1, 2, 1, 2],
"value": [1.2 , 3.5, 5.4, 7.1, 6.4, 1.8, 3.5, 5.6]
})
看起来像这样:
我想创建一个嵌套字典,将列“颜色”和“对象”作为字符串的第一个键(例如"(blue, hat)"
(注意:这是一个语法不正确的元组。它应该是字符串格式!),组作为第二级的键,值作为第二级的键。即我想要的输出是:
{
"(blue, hat)": {
1: 1.2,
2: 3.5
},
"(blue, coat)": {
1: 5.4,
2: 7.1
},
"(green, hat)": {
1: 6.4,
2: 1.8
},
"(green, coat)": {
1: 3.5,
2: 5.6
}
}
我的方法是遍历 和 的唯一值,color
但这对我来说似乎很麻烦。有没有更蟒蛇的方法?object
group
解决方案
使用字典DataFrame.groupby
推导,如果需要像字符串一样的元组rept,请使用:
d = {str(k): v.set_index('group')['value'].to_dict()
for k, v in df.groupby(['color','object'])}
print (d)
{
"('blue', 'coat')": {
1: 5.4,
2: 7.1
},
"('blue', 'hat')": {
1: 1.2,
2: 3.5
},
"('green', 'coat')": {
1: 3.5,
2: 5.6
},
"('green', 'hat')": {
1: 6.4,
2: 1.8
}
或者如果需要像'tuple'
s 一样改变格式而不''
使用f-string
s:
d = {f'({k[0]}, {k[1]})': v.set_index('group')['value'].to_dict()
for k, v in df.groupby(['color','object'])}
替代join
:
d = {f'({", ".join(k)})': v.set_index('group')['value'].to_dict()
for k, v in df.groupby(['color','object'])}
print (d)
{
'(blue, coat)': {
1: 5.4,
2: 7.1
},
'(blue, hat)': {
1: 1.2,
2: 3.5
},
'(green, coat)': {
1: 3.5,
2: 5.6
},
'(green, hat)': {
1: 6.4,
2: 1.8
}
}
推荐阅读
- r - 列表中的函数可以访问 R 中列表的属性吗?
- mysql - MySQL/MariaDB:无法使用正确的权限和用户进行更改。不是密码问题
- android - NavigationDrawer 上的项目未单击
- python - 如何与前一组(月)的同一行执行自联接以在 Pyspark 中引入具有不同表达式的附加列
- mongodb - 无法使用 mongoose 将数组数据插入 mongodb
- c# - Xamarin - 使用 PCLStorage 镜像时 IO 操作失败
- reactjs - react-beautiful-dnd 结合了水平和垂直方向
- python - 保存使用 BeautifulSoup 获取的全部数据
- bash - 将常用命令提取到函数中
- javascript - 笑话:如何在(仅)一个单独的测试后拆解