我有一個大資料框,這是一個摘錄:
| 指數 | 協議 ID | 活動編號 | 細節 1 | 細節 2 |
|---|---|---|---|---|
| 0 | 1509 | 15 | 一個 | s |
| 1 | 636 | 159 | b | 噸 |
| 2 | 787 | 159 | C | 你 |
| 3 | 796 | 159 | d | v |
| 4 | 1174 | 159 | e | w |
| 5 | 787 | 252 | F | X |
| 6 | 1029 | 252 | G | 是的 |
| 7 | 1188 | 鈉 | H | z |
| 8 | 1848年 | 鈉 | 一世 | 一個 |
| 9 | 待定 | 鈉 | j | b |
| 10 | 待定 | 鈉 | ? | C |
| 11 | 1029 | 253 | l | d |
| 12 | 1170 | 253 | 米 | e |
| 13 | 1468 | 鈉 | n | F |
| 14 | 957 | 鈉 | ○ | G |
| 15 | 1029 | 254 | p | H |
| 16 | 957 | 254 | q | 一世 |
| 17 | 841 | 166 | r | j |
我需要創建一個由 Activity ID 命名的字典。在每個“活動字典”中,我需要由協議 ID 命名的所有資料幀,并且在每個協議資料幀中,我需要來自所有初始列的完整資訊。
所以,活動字典 → 在每一個中,它們的協議字典 → 在每一個中,與協議相關的所有資訊的資料框
當我編碼時
activity_dict = initial_dataframe.set_index('Activity ID').T.to_dict('dict')
它確實為我創建了一個由活動 ID 命名的字典,但是當我單擊一個活動時,它只顯示最后一個協議和鏈接到它的資訊。因為這基本上是在做我需要的最后一步,所以我試圖添加中間步驟,即當我單擊活動字典或運行時應該出現的協議資料幀,例如:
activity_dict["159"]
現在正在向我展示
{'Protocol ID': '1174',
'Protocol Name': 'My analyses',
'I/O': 'O',
'Prot Owner': 'lorem.ipsum',
'Notes': 'Done',
'Activity Name': 'Test',
'Comments': nan,
'Activity Owner': nan,
'Protocol description': nan,
'Fonte': nan}
當我想讓它向我顯示一個鏈接到不僅鏈接到協議 1174,還鏈接到 636 和 787 的資料幀時。
有人知道怎么做這個嗎?
先感謝您
uj5u.com熱心網友回復:
因為字典具有唯一鍵,一種可能的解決方案是為所有值創建串列:
activity_dict = initial_dataframe.groupby('Activity ID').agg(list).to_dict('index')
print (activity_dict)
{'15': {'Protocol ID': ['1509'], 'Detail 1': ['a'], 'Detail 2': ['s']},
'159': {'Protocol ID': ['636', '787', '796', '1174'], 'Detail 1': ['b', 'c', 'd', 'e'], 'Detail 2': ['t', 'u', 'v', 'w']},
'166': {'Protocol ID': ['841'], 'Detail 1': ['r'], 'Detail 2': ['j']},
'252': {'Protocol ID': ['787', '1029'], 'Detail 1': ['f', 'g'], 'Detail 2': ['x', 'y']},
'253': {'Protocol ID': ['1029', '1170'], 'Detail 1': ['l', 'm'], 'Detail 2': ['d', 'e']},
'254': {'Protocol ID': ['1029', '957'], 'Detail 1': ['p', 'q'], 'Detail 2': ['h', 'i']}}
或使用加入:
activity_dict = initial_dataframe.groupby('Activity ID').agg(','.join).to_dict('index')
print (activity_dict)
{'15': {'Protocol ID': '1509', 'Detail 1': 'a', 'Detail 2': 's'},
'159': {'Protocol ID': '636,787,796,1174', 'Detail 1': 'b,c,d,e', 'Detail 2': 't,u,v,w'},
'166': {'Protocol ID': '841', 'Detail 1': 'r', 'Detail 2': 'j'},
'252': {'Protocol ID': '787,1029', 'Detail 1': 'f,g', 'Detail 2': 'x,y'},
'253': {'Protocol ID': '1029,1170', 'Detail 1': 'l,m', 'Detail 2': 'd,e'},
'254': {'Protocol ID': '1029,957', 'Detail 1': 'p,q', 'Detail 2': 'h,i'}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495567.html
下一篇:從整數轉換為具有重復數字的字典
