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

