python - 熊猫数据框到具有特定格式的字典
问题描述
我有一个这样的df:
Customer# Facility Transp
1 RS 4
2 RS 7
3 RS 9
1 CM 2
2 CM 8
3 CM 5
I want to convert to a dictionary that looks like this:
transp = {'RS' : {1 : 4, 2 : 7, 3 : 9,
'CM' : {1 : 2, 2 : 8, 3 : 5}}
我不熟悉这种转换。我尝试了各种选择。数据必须完全采用这种字典格式。我不能用 [] 嵌套。本质上,设施是主要级别,然后是客户/运输。我觉得这应该很容易......谢谢,
解决方案
您可以一口气完成。
df = pd.DataFrame({"Customer#": [1, 2, 3, 1, 2, 3],
"Facility": ['RS', 'RS', 'RS', 'CM', 'CM', 'CM'],
"Transp": [4, 7, 9, 2, 8, 5]})
transp = df.groupby('Facility')[['Customer#','Transp']].apply(lambda g: dict(g.values.tolist())).to_dict()
print(transp)
推荐阅读
- javascript - 优化更新或推入大数组
- html - 如何正确地将我的语言字符输出到 C++ 中的 HTML 文件?
- multithreading - smt 模式下的多线程程序只运行一个线程 gem5
- python - 带暂停的函数循环
- python - Internet Explorer 11 - Cookie 不保存通过的会话
- c# - 使用 ASP.net 核心应用程序访问受保护的目录
- javascript - 有没有一种安全的方法来防止 exec 剥离引号?
- python - tkinter python中的标签是否有任何命令属性?
- c++ - 如何将 SSAO 应用于天空盒?
- javascript - 如何在 Angular Firebase 中修复浏览器刷新时的“TypeError:无法读取属性 'getIdToken' of null”?