我有一个带有节点和边缘的数据框:点击查看数据框的图像
我想创建的字典的字典,像这样:dict ={125730:{268675130: 8.707, 4761621113: 132.800, 244455548: 105.925, 60912980:130.717}, 8149548972:{8149548986: 4.439, 8149548986: 117.778}, 8149548979等....
但是我找不到解决办法…你能帮我吗?谢谢
您可以使用:
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] |
'''
然后组合边距离和列作为字典:
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 [' 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
}
}
import pandas as pd
df = pd.read_csv("test.csv")
df_dict = df.to_dict()
print(df_dict)