Python中DataFrame與內(nèi)置數(shù)據(jù)結(jié)構(gòu)相互轉(zhuǎn)換的實(shí)現(xiàn)
楔子
pandas 支持我們從 Excel、CSV、數(shù)據(jù)庫(kù)等不同數(shù)據(jù)源當(dāng)中讀取數(shù)據(jù),來(lái)構(gòu)建 DataFrame。但有時(shí)數(shù)據(jù)并不來(lái)自這些外部數(shù)據(jù)源,而是來(lái)自一個(gè)已經(jīng)存在的 Python 數(shù)據(jù)結(jié)構(gòu),比如列表、字典等等。
同理當(dāng)需要導(dǎo)出 DataFrame 時(shí),也不一定非要寫(xiě)到外部文件里,而是希望生成字典或者列表,那么這個(gè)時(shí)候該怎么做呢?
所以這就涉及到了 DataFrame 和 Python 內(nèi)置數(shù)據(jù)結(jié)構(gòu)之間的相互轉(zhuǎn)換,下面來(lái)介紹一些最佳實(shí)踐,你可以根據(jù)實(shí)際情況進(jìn)行選擇。
DataFrame 轉(zhuǎn)成內(nèi)置數(shù)據(jù)結(jié)構(gòu)
假設(shè)有這樣一個(gè) DataFrame:
import?pandas?as?pd df?=?pd.DataFrame({"name":?["Satori",?"Koishi",?"Marisa"], ???????????????????"score":?[99,?98,?100], ???????????????????"rank":?[2,?3,?1]}) print(df) """ ?????name??score??rank 0??Satori?????99?????2 1??Koishi?????98?????3 2??Marisa????100?????1 """
那么看看 DataFrame 都提供了哪些方法,以及在轉(zhuǎn)成內(nèi)置數(shù)據(jù)結(jié)構(gòu)之后是什么樣子?
df.to_records()
將 DataFrame 轉(zhuǎn)成 Numpy 的數(shù)組,數(shù)組里面是一個(gè)個(gè)的元組。
print(df.to_records()) """ [(0,?'Satori',??99,?2)?(1,?'Koishi',??98,?3)?(2,?'Marisa',?100,?1)] """ #?返回的時(shí)候?qū)⑺饕矌狭?,我們可以去? print(df.to_records(index=False)) """ [('Satori',??99,?2)?('Koishi',??98,?3)?('Marisa',?100,?1)] """ #?df.to_records?返回的是?numpy?的數(shù)組,可以再轉(zhuǎn)成列表 print(df.to_records(index=False).tolist()) """ [('Satori',?99,?2),?('Koishi',?98,?3),?('Marisa',?100,?1)] """
這種數(shù)據(jù)結(jié)構(gòu)還是很常見(jiàn)的,在工作中經(jīng)常會(huì)用到。但唯一不好的是,字段信息丟失了。
df.to_dict()
將 DataFrame 轉(zhuǎn)成 Python 的字典。
#?返回?Python?的字典,key?是字段名,value?是對(duì)應(yīng)的每一列 print(df.to_dict()) """ {'name':?{0:?'Satori',?1:?'Koishi',?2:?'Marisa'}, ?'rank':?{0:?2,?1:?3,?2:?1}, ?'score':?{0:?99,?1:?98,?2:?100}} """ #?但這里的?value?有一些問(wèn)題,就是它把索引也包含在里面了 #?我們可以去掉它 print( ????{k:?tuple(v.values())?for?k,?v?in?df.to_dict().items()} ) """ {'name':?('Satori',?'Koishi',?'Marisa'), ?'rank':?(2,?3,?1), ?'score':?(99,?98,?100)} """ #?當(dāng)然啦,to_dict()?還可以手動(dòng)實(shí)現(xiàn) print( ????{col:?tuple(df[col])?for?col?in?df.columns} ) """ {'name':?('Satori',?'Koishi',?'Marisa'), ?'rank':?(2,?3,?1), ?'score':?(99,?98,?100)} """
這種格式的數(shù)據(jù)用的就不多了,用得更多的是下一種。
df.to_dict(orient="records")
將 DataFrame 轉(zhuǎn)成 Python 的列表,列表里面是一個(gè)個(gè)的字典,每個(gè)字典代表數(shù)據(jù)的每一行。
print(df.to_dict(orient="records")) """ [{'name':?'Satori',?'rank':?2,?'score':?99}, ?{'name':?'Koishi',?'rank':?3,?'score':?98}, ?{'name':?'Marisa',?'rank':?1,?'score':?100}] """
個(gè)人覺(jué)得這種數(shù)據(jù)結(jié)構(gòu)應(yīng)該用得最多。
DataFrame 生成的數(shù)據(jù)還有其它格式,這里就不贅述了,常用的就是上面幾種。
內(nèi)置數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)成 DataFrame
內(nèi)置數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)成 DataFrame,我們也來(lái)介紹幾個(gè)最常用的場(chǎng)景。
import?pandas?as?pd data?=?[{'name':?'Satori',?'rank':?2,?'score':?99}, ????????{'name':?'Koishi',?'rank':?3,?'score':?98}, ????????{'name':?'Marisa',?'rank':?1,?'score':?100}] #?對(duì)于這種數(shù)據(jù),可以通過(guò)?DataFrame?的?from_records?方法 #?列表里的字典代表了?DataFrame?的每一行,每個(gè)字典都具有相同的?key #?而這些?key?則表示?DataFrame?的列 print(pd.DataFrame.from_records(data)) """ ?????name??rank??score 0??Satori?????2?????99 1??Koishi?????3?????98 2??Marisa?????1????100 """ #?或者更簡(jiǎn)單的,直接調(diào)用?pd.DataFrame?即可 print(pd.DataFrame(data)) """ ?????name??rank??score 0??Satori?????2?????99 1??Koishi?????3?????98 2??Marisa?????1????100 """ #?如果列表里面的字典,不具備相同的 key,會(huì)怎么樣呢? data[2]["length"]?=?155 print(pd.DataFrame(data)) """ ?????name??rank??score??length 0??Satori?????2?????99?????NaN 1??Koishi?????3?????98?????NaN 2??Marisa?????1????100???155.0 """ #?很簡(jiǎn)單,會(huì)將所有的?key?都考慮在內(nèi) #?如果某一行沒(méi)有指定的?key,那么對(duì)應(yīng)的值就是空
當(dāng)然數(shù)據(jù)也可能是這種格式:
import?pandas?as?pd data?=?{'2020-01-01':?{'name':?'Satori',?'rank':?2,?'score':?99}, ????????'2020-01-02':?{'name':?'Koishi',?'rank':?3,?'score':?98}, ????????'2020-01-03':?{'name':?'Marisa',?'rank':?1,?'score':?100}} print(pd.DataFrame.from_dict(data,?orient="index")) """ ??????????????name??rank??score 2020-01-01??Satori?????2?????99 2020-01-02??Koishi?????3?????98 2020-01-03??Marisa?????1????100 """
最后一種:
import?pandas?as?pd data?=?{'name':?['Satori',?'Koishi',?'Marisa'], ????????'rank':?[2,?3,?1], ????????'score':?[99,?98,?100]} #?直接調(diào)用?DataFrame?即可 print(pd.DataFrame(data)) """ ?????name??rank??score 0??Satori?????2?????99 1??Koishi?????3?????98 2??Marisa?????1????100 """
上面就是本文的內(nèi)容,比較簡(jiǎn)單。并且相關(guān)函數(shù)的具體用法,也沒(méi)有詳細(xì)說(shuō)明,只是從工作角度介紹了一些最佳實(shí)踐。更多內(nèi)容,可以查看 pandas 的注釋。
到此這篇關(guān)于Python中DataFrame與內(nèi)置數(shù)據(jù)結(jié)構(gòu)相互轉(zhuǎn)換的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python DataFrame內(nèi)置數(shù)據(jù)結(jié)構(gòu)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python和shell實(shí)現(xiàn)的校驗(yàn)IP地址合法性腳本分享
這篇文章主要介紹了python和shell實(shí)現(xiàn)的校驗(yàn)IP地址合法性腳本分享,每個(gè)腳本配有執(zhí)行效果圖,需要的朋友可以參考下2014-10-10Python爬蟲(chóng)學(xué)習(xí)之獲取指定網(wǎng)頁(yè)源碼
這篇文章主要為大家詳細(xì)介紹了Python爬蟲(chóng)學(xué)習(xí)之獲取指定網(wǎng)頁(yè)源碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07Python 快速實(shí)現(xiàn)CLI 應(yīng)用程序的腳手架
本篇文章主要介紹了Python 快速實(shí)現(xiàn)CLI 應(yīng)用程序的腳手架,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12Python pygame繪制文字制作滾動(dòng)文字過(guò)程解析
這篇文章主要介紹了Python pygame繪制文字制作滾動(dòng)文字過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12python:批量統(tǒng)計(jì)xml中各類(lèi)目標(biāo)的數(shù)量案例
這篇文章主要介紹了python:批量統(tǒng)計(jì)xml中各類(lèi)目標(biāo)的數(shù)量案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03