【问题标题】:How to create a dictionary from a CSV with two columns as the key in Python [duplicate]如何从 CSV 创建字典,其中两列作为 Python 中的键 [重复]
【发布时间】: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


    【解决方案1】:

    IIUC 你很接近 - 需要['Column-3'] 选择列:

    d = df.set_index(['Column-1', 'Column-2'])['Column-3'].to_dict()
    print (d)
    {(2, 'B'): 'bar', (1, 'A'): 'foo'}
    

    【讨论】:

      【解决方案2】:

      选项 1

      dict(zip(zip(df['Column-1'], df['Column-2']), df['Column-3']))
      
      {(1, 'A'): 'foo', (2, 'B'): 'bar'}
      

      选项 2

      {(a, b): c for a, b, c in df.values}
      
      {(1, 'A'): 'foo', (2, 'B'): 'bar'}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 2016-02-27
        • 2023-03-20
        • 2014-11-11
        • 1970-01-01
        相关资源
        最近更新 更多