【发布时间】:2018-09-16 02:24:10
【问题描述】:
我正在尝试从具有 3 列的 CSV 创建一个字典,其中前两列成为键,第三列成为值:
在本例中,example.csv 包含:
Column-1 Column-2 Column-3
1 A foo
2 B bar
预期的输出应该是:
dictionary = {1, A: foo, 2, B: bar}
我目前正在尝试从 pandas 数据框导入并转换为字典。我使用以下失败:
df = pd.read_csv("example.csv")
dictionary = df.set_index(['Column-1', 'Column-2']).to_dict()
有没有办法使用 pandas 来创建字典,或者有更优雅的方法将 csv 转换为字典?
【问题讨论】:
标签: python pandas csv dictionary