【问题标题】:How can I make a square matrix from a nested dict?如何从嵌套字典中制作方阵?
【发布时间】:2020-10-30 04:49:01
【问题描述】:

我最近在使用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(Networkx: Get the distance between nodes),我设法知道数据集是如何编码为嵌套字典的。

问题是,我不熟悉字典。如果是嵌套列表,我可以处理,但是嵌套的dict...我需要其他人的帮助。

所以我检查了如果我这样编写代码会给我带来什么:

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  ...
...

请各位大神赐教好吗? 感谢您抽出宝贵时间查看此问题,并提前感谢您的解决方案。

【问题讨论】:

    标签: python-3.x pandas dataframe dictionary networkx


    【解决方案1】:

    我刚刚做了一个清单。

    dis = dict(nx.all_pairs_shortest_path_length(graph))

    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])
    

    感谢大家解决这个问题。 祝您有美好的一天!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2020-12-21
      • 2021-10-12
      • 2021-09-03
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多