【问题标题】:create a dictionary from a dataframe in Python从 Python 中的数据框创建字典
【发布时间】:2016-05-09 10:05:57
【问题描述】:

对于以下数据,我如何创建一个字典,其中 id 作为元组数组 [(x, y)] 的键和值

  id  x  y
0  a  1  2
1  a  2  3
2  b  3  4

预期的字典是

{a: [(1,2), (2,3)], b:[(3,4)]}

【问题讨论】:

标签: python dictionary


【解决方案1】:

在遍历表时(不管你在做什么)检查 id 是否已经在 dict 中并附加到现有值或添加新键:

data = {}
for id,x,y in SOURCE:
    if id in data:
        data[id].append((x,y))
    else:
        data[id] = [(x,y)]

【讨论】:

    【解决方案2】:

    @tadhg-mcdonald-jensen 提供的解决方案似乎是利用 defaultdict 的绝佳机会:

    from collections import defaultdict
    
    data = defaultdict(list)
    
    with open(SOURCE_FILE_NAME) as source:
        for line in source:
            id, x, y = line.rstrip().split()
            data[id].append((x, y))
    

    这避免了设置或附加的决定 - 只需附加并让 defaultdict 为您做正确的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      相关资源
      最近更新 更多