當前位置:成語大全網 - 漢語詞典 - 把壹行數據幀變成字典python。

把壹行數據幀變成字典python。

有時候在Python中,需要將dataframe類型轉換為dictionary類型,下面的方法幫助我們解決這個問題。任務代碼。

#編碼:utf-8

進口熊貓作為pd

a = ['姓名','年齡','性別']

b = ['阿裏',' 19 ','中國']

數據= pd。DataFrame(zip(a,b),columns=['project ',' attribute'])

打印數據

dict _ country = data . set _ index(' project '). t . to _ dict(' list ')

打印字典_國家

輸出顯示

項目屬性

0名阿裏

1年齡19

2性別中國

{ '性別':['中國'],'年齡':['19'],'姓名':['阿裏']}

值得註意的是,換位前需要設置指定的索引,否則會根據默認索引轉換成這個:

{0: ['姓名','阿裏'],1: ['年齡',' 19'],2: ['性別','中國']}