1

我有格式的数据

from        to
Location1   Location2
Location1   Location3
Location1   Location4
Location1   Location5

Location2   Location1
Location2   Location3

Location3   Location1
Location3   Location2
Location3   Location4

在一个 csv 文件中。这些数据绘制了从一个站点到另一个站点的自行车旅行地图,取自芝加哥一家自行车租赁公司的网站。

现在我有基本的代码,它把每一行添加到一个列表中,但它并没有像我希望的那样在第二个索引中创建一个字典。我的脚本看起来像:

import csv
li = []
with open('Desktop/test_Q4_trips.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for name, imports in reader:
    li.append({
        "name": name,
        "imports": imports,
    })
del li[0]

这是输出,

[{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"},
{"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}, 
...]

我想把这些数据转换成这种格式,

[{"from": "Location1", "to": ["Location2", "Location3", "Location4", "Location5"]},
    {"from": "Location2", "to": ["Location1", "Location3"]},
    {"from": "Location3", "to": ["Location1", "Location2", "Location4"]}, ...
].

换句话说,我想创建一个字典列表,其中每个字典在第一个索引中有一个值,在第二个索引中有一个(可变多个)值列表。特别是,输出应在第二个索引的列表中列出自行车租赁行程接收端的所有站点。为此,我想我将不得不创建一个带有 for 循环的脚本,该循环遍历左侧的“from”值,并将与每个“from”对应的每个“to”位置附加到列表中。

我希望我的数据采用我提到的特定形式,以便使用我拥有的数据可视化代码。我确信创建我想要的格式需要思想上的飞跃,但我不确定该怎么做才能满足这一点。我也不确定我需要的输出类型应该是列表还是数组,希望对此进行澄清。

请帮我解决这个问题,在此先感谢。

4

2 回答 2

2

collections.defaultdict可能是解决这个问题的好方法。

from collections import defaultdict


d = defaultdict(list)

a = [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"},
     {"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}]


for o in a:
    d[o['from']].append(o['to'])

print(d)
于 2018-08-24T02:20:43.247 回答
0

我认为这应该可行

import numpy as np
l = [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"},
 {"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}]

from_to = np.array(([d['from'] for d in l],[d['to'] for d in l])).T
froms = set(from_to[:,0])

out = []
for f in froms: 
    d = {}
    mask = from_to[:,0]==f
    d['from']=f
    d['to'] = from_to[:,1][mask]
    out.append(d)
于 2018-08-24T02:22:54.890 回答