簡介:pandas 中的to_dict 可以對DataFrame類型的數據進行轉換
可以選擇六種的轉換類型,分別對應于參數 ‘dict', ‘list', ‘series', ‘split', ‘records', ‘index',下面逐一介紹每種的用法
Help on method to_dict in module pandas.core.frame:to_dict(orient='dict') method of pandas.core.frame.DataFrame instance Convert DataFrame to dictionary. Parameters ---------- orient : str {'dict', 'list', 'series', 'split', 'records', 'index'} Determines the type of the values of the dictionary. - dict (default) : dict like {column -> {index -> value}} - list : dict like {column -> [values]} - series : dict like {column -> Series(values)} - split : dict like {index -> [index], columns -> [columns], data -> [values]} - records : list like [{column -> value}, ... , {column -> value}] - index : dict like {index -> {column -> value}} .. versionadded:: 0.17.0 Abbreviations are allowed. `s` indicates `series` and `sp` indicates `split`. Returns ------- result : dict like {column -> {index -> value}}
1、選擇參數orient='dict'
dict也是默認的參數,下面的data數據類型為DataFrame結構, 會形成 {column -> {index -> value}}這樣的結構的字典,可以看成是一種雙重字典結構
- 單獨提取每列的值及其索引,然后組合成一個字典
- 再將上述的列屬性作為關鍵字(key),值(values)為上述的字典
查詢方式為 :data_dict[key1][key2]
- data_dict 為參數選擇orient='dict'時的數據名
- key1 為列屬性的鍵值(外層)
- key2 為內層字典對應的鍵值
data Out[9]: pclass age embarked home.dest sex1086 3rd 31.194181 UNKNOWN UNKNOWN male12 1st 31.194181 Cherbourg Paris, France female1036 3rd 31.194181 UNKNOWN UNKNOWN male833 3rd 32.000000 Southampton Foresvik, Norway Portland, ND male1108 3rd 31.194181 UNKNOWN UNKNOWN male562 2nd 41.000000 Cherbourg New York, NY male437 2nd 48.000000 Southampton Somerset / Bernardsville, NJ female663 3rd 26.000000 Southampton UNKNOWN male669 3rd 19.000000 Southampton England male507 2nd 31.194181 Southampton Petworth, Sussex maleIn[10]: data_dict=data.to_dict(orient= 'dict')In[11]: data_dictOut[11]: {'age': {12: 31.19418104265403, 437: 48.0, 507: 31.19418104265403, 562: 41.0, 663: 26.0, 669: 19.0, 833: 32.0, 1036: 31.19418104265403, 1086: 31.19418104265403, 1108: 31.19418104265403}, 'embarked': {12: 'Cherbourg', 437: 'Southampton', 507: 'Southampton', 562: 'Cherbourg', 663: 'Southampton', 669: 'Southampton', 833: 'Southampton', 1036: 'UNKNOWN', 1086: 'UNKNOWN', 1108: 'UNKNOWN'}, 'home.dest': {12: 'Paris, France', 437: 'Somerset / Bernardsville, NJ', 507: 'Petworth, Sussex', 562: 'New York, NY', 663: 'UNKNOWN', 669: 'England', 833: 'Foresvik, Norway Portland, ND', 1036: 'UNKNOWN', 1086: 'UNKNOWN', 1108: 'UNKNOWN'}, 'pclass': {12: '1st', 437: '2nd', 507: '2nd', 562: '2nd', 663: '3rd', 669: '3rd', 833: '3rd', 1036: '3rd', 1086: '3rd', 1108: '3rd'}, 'sex': {12: 'female', 437: 'female', 507: 'male', 562: 'male', 663: 'male', 669: 'male', 833: 'male', 1036: 'male', 1086: 'male', 1108: 'male'}}
新聞熱點
疑難解答