pandas 将三列转换为字典的字典

gojuced7  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(164)

我有一个包含节点和边的 Dataframe ,如下所示:Click to see the image of dataframe
我想创建这样的字典的字典:法令= {125730:{268675130:8.707、4761621113:132.800、二四四四五五四八:105.925、60912980:130.717、8149548972:电话:8149548986 4.439、8149548986:第117.778条、第8149548979条等
但是我找不到解决办法...你能帮我吗?谢谢

bbmckpt7

bbmckpt71#

import pandas as pd
df = pd.read_csv("test.csv")
df_dict = df.to_dict()
print(df_dict)
jyztefdp

jyztefdp2#

您可以用途:

dfx=df.groupby('Nodes').agg(list)

'''
|      Nodes | Edges                                          | Distance                       |
|-----------:|:-----------------------------------------------|:-------------------------------|
|     125730 | [268675130, 4761621113, 244455548, 1089076050] | [8707, 132800, 105925, 124290] |
|     125742 | [60912980]                                     | [130717]                       |
| 8149548972 | [8149548986, 8149548957]                       | [4439, 117778]                 |
| 8149548979 | [8149548986]                                   | [33505]                        |
| 8149548986 | [8112651374, 8149548979]                       | [44980, 33505]                 |
'''

然后将EdgesDistance列合并为字典:

dfx['to_dict']=dfx.apply(lambda x: dict(zip(x['Edges'], x['Distance'])),axis=1)

'''
|      Nodes | to_dict                                                                      |
|-----------:|:-----------------------------------------------------------------------------|
|     125730 | {268675130: 8707, 4761621113: 132800, 244455548: 105925, 1089076050: 124290} |
|     125742 | {60912980: 130717}                                                           |
| 8149548972 | {8149548986: 4439, 8149548957: 117778}                                       |
| 8149548979 | {8149548986: 33505}                                                          |
| 8149548986 | {8112651374: 44980, 8149548979: 33505}                                       |
'''

使用dfx.index和**dfx['to_dict']**创建字典:

final=dict(zip(dfx.index, dfx['to_dict']))

输出

{
  "125730": {
    "244455548": 105925,
    "268675130": 8707,
    "1089076050": 124290,
    "4761621113": 132800
  },
  "125742": {
    "60912980": 130717
  },
  "8149548972": {
    "8149548986": 4439,
    "8149548957": 117778
  },
  "8149548979": {
    "8149548986": 33505
  },
  "8149548986": {
    "8112651374": 44980,
    "8149548979": 33505
  }
}

相关问题