简体   繁体   English

Python Excel 文件到字典

[英]Python Excel file to Dictionary

I would like to create depandant combobox from the Excel file.我想从 Excel 文件创建 depandant 组合框。 If the combo1 is selected, the combo2 will be changed depending on Combo1.如果选择了组合 1,组合 2 将根据组合 1 进行更改。 The input is as below.输入如下。

City城市 Name名称
AA机管局 John约翰
AA机管局 Anne安妮
BB BB Sean肖恩
BB BB Dylan迪伦

I have tried to create Pandas dataframe and use to_dict().我尝试创建 Pandas 数据框并使用 to_dict()。 But it was not the result I expect.但这不是我期望的结果。

The expected result {"AA": [["John"], ["Anne"]], "BB": [["Sean"], ["Dylan"]]}.预期结果 {"AA": [["John"], ["Anne"]], "BB": [["Sean"], ["Dylan"]]}。

Thank you.谢谢你。

Edit : Code I have tried.编辑:我试过的代码。 If combo1 "AA" is selected, combo2 will display "John","Anne"如果选择combo1“AA”,combo2将显示“John”、“Anne”

df = (pd.read_excel("test.xls"))

#due to I don't need the "City" && "Name".
df.set_index('City')['Name'].to_dict()  

Output : {'AA': 'Anne', 'BB': 'Dylan'}输出: {'AA': 'Anne', 'BB': 'Dylan'}

df.to_dict("r")

Output : [{'City': 'AA', 'Name': 'John'}, {'City': 'AA', 'Name': 'Anne'}, {'City': 'BB', 'Name': 'Sean'}, {'City': 'BB', 'Name': 'Dylan'}]输出: [{'City': 'AA', 'Name': 'John'}, {'City': 'AA', 'Name': 'Anne'}, {'City': 'BB', 'Name': 'Sean'}, {'City': 'BB', 'Name': 'Dylan'}]

df.to_dict("list")

Output : {'City': ['AA', 'AA', 'BB', 'BB'], 'Name': ['John', 'Anne', 'Sean', 'Dylan']}输出: {'City': ['AA', 'AA', 'BB', 'BB'], 'Name': ['John', 'Anne', 'Sean', 'Dylan']}

Try via groupby() , agg() and to_dict() method:尝试通过groupby() , agg()to_dict()方法:

out=df.groupby('City')['Name'].agg(list).to_dict()
#you can also use apply() in place of agg() method

output of out : out输出:

{'AA': ['John', 'Anne'], 'BB': ['Sean', 'Dylan']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM