如何从嵌套字典制作方阵?
How can I make a square matrix from a nested dict?
我最近在使用networkx模块,现在要获取各国之间的距离数据
所以 excel 原始数据是这样的:
Nat1 Nat2 Y/N
ABW ANT 0
ABW ARG 0
ABW BEK 1
ABW BHS 1
ABW BRA 0
...
ALB COL 0
ALB CYP 1
...
感谢 GeckStar(),我设法知道数据集是如何编码的,作为一个嵌套字典。
问题是,我不熟悉字典。如果是嵌套列表,我可以处理,但是嵌套字典...我需要其他人的帮助。
所以我检查了如果我这样编码会给我带来什么:
distance = dict(nx.all_pairs_shortest_path_length(graph))
df = pd.DataFrame(list(distance.items()))
df.to_excel("C_C.xlsx")
(仅供参考,
distance = dict(nx.all_pairs_shortest_path_length(graph))
将计算从一个国家到另一个国家的最短路径。因此,如果一个国家与另一个国家没有联系,需要绕行,它的价值将大于 1。)
当然,并不顺利。
0 1
0 ABW {'ABW':0, 'ANT': 1 ..., 'BHS': 2 ...}
1 ANT {'ANT':0, 'ABW': 1 ...}
...
3 BEL {'BEL':0, 'ABW':1, ... 'BHS':4, ...}
...
但我知道应该有一种方法可以将这些数据变成这样的方阵:
ABW ANT ARG BEL BHS ...
ABW 0 0 0 1 2 ...
ANT 0 0 1 0 1 ...
ARG 0 1 0 1 0 ...
BEL 2 0 1 0 4 ...
...
请各位大神赐教?
感谢您花时间查看,并提前感谢您的解决方案。
我刚刚用列表做了一个演练。
dis = dict(nx.all_pairs_shortest_path_length(图表))
Nations = list(dis.keys())
master = [[""]]
for x in Nations:
master[0].append(x)
for Nat1 in dis:
master.append([Nat1])
for Nat2 in Nations:
master[-1].append(dis[Nat1][Nat2])
感谢大家解决这个问题。
祝你有美好的一天!
我最近在使用networkx模块,现在要获取各国之间的距离数据
所以 excel 原始数据是这样的:
Nat1 Nat2 Y/N
ABW ANT 0
ABW ARG 0
ABW BEK 1
ABW BHS 1
ABW BRA 0
...
ALB COL 0
ALB CYP 1
...
感谢 GeckStar(
问题是,我不熟悉字典。如果是嵌套列表,我可以处理,但是嵌套字典...我需要其他人的帮助。
所以我检查了如果我这样编码会给我带来什么:
distance = dict(nx.all_pairs_shortest_path_length(graph))
df = pd.DataFrame(list(distance.items()))
df.to_excel("C_C.xlsx")
(仅供参考,
distance = dict(nx.all_pairs_shortest_path_length(graph))
将计算从一个国家到另一个国家的最短路径。因此,如果一个国家与另一个国家没有联系,需要绕行,它的价值将大于 1。)
当然,并不顺利。
0 1
0 ABW {'ABW':0, 'ANT': 1 ..., 'BHS': 2 ...}
1 ANT {'ANT':0, 'ABW': 1 ...}
...
3 BEL {'BEL':0, 'ABW':1, ... 'BHS':4, ...}
...
但我知道应该有一种方法可以将这些数据变成这样的方阵:
ABW ANT ARG BEL BHS ...
ABW 0 0 0 1 2 ...
ANT 0 0 1 0 1 ...
ARG 0 1 0 1 0 ...
BEL 2 0 1 0 4 ...
...
请各位大神赐教? 感谢您花时间查看,并提前感谢您的解决方案。
我刚刚用列表做了一个演练。
dis = dict(nx.all_pairs_shortest_path_length(图表))
Nations = list(dis.keys())
master = [[""]]
for x in Nations:
master[0].append(x)
for Nat1 in dis:
master.append([Nat1])
for Nat2 in Nations:
master[-1].append(dis[Nat1][Nat2])
感谢大家解决这个问题。 祝你有美好的一天!