溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何用Python處理數(shù)據(jù)

發(fā)布時(shí)間:2021-06-23 15:17:54 來(lái)源:億速云 閱讀:163 作者:chen 欄目:編程語(yǔ)言

這篇文章主要介紹“如何用Python處理數(shù)據(jù)”,在日常操作中,相信很多人在如何用Python處理數(shù)據(jù)問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”如何用Python處理數(shù)據(jù)”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

工欲善其事,必先利其器!我們想要更輕松更有效率地開發(fā),必須學(xué)會(huì)一些“高級(jí)”技能。前不久看到一位 Python 高僧的代碼,其中使用了一個(gè)短小精悍的模塊,我認(rèn)為還蠻有用的,今天分享給大家。

這個(gè)模塊就叫 glom ,是 Python 處理數(shù)據(jù)的一個(gè)小模塊,它具有如下特點(diǎn):

  • 嵌套結(jié)構(gòu)并基于路徑訪問(wèn)

  • 使用輕量級(jí)的Pythonic規(guī)范進(jìn)行聲明性數(shù)據(jù)轉(zhuǎn)換

  • 可讀、有意義的錯(cuò)誤信息

  • 內(nèi)置數(shù)據(jù)探測(cè)和調(diào)試功能

看起來(lái)比較抽象,對(duì)不對(duì)?下面我們用實(shí)例來(lái)給大家演示一下。

安裝

作為 Python 內(nèi)置模塊,相信你一定知道怎么安裝:

pip3 install glom

幾秒鐘就搞定!

簡(jiǎn)單使用

我們來(lái)看看最簡(jiǎn)單的用法:

d = {"a": {"b": {"c": 1}}}
print(glom(d, "a.b.c")) # 1

在這里,我們有一個(gè)嵌套三層的 json 結(jié)構(gòu),我們想獲取最里層的 c 對(duì)應(yīng)的值,正常的寫法應(yīng)該是:

print(d["a"]["b"]["c"])

如果到這里,我說(shuō) glom 比傳統(tǒng)方式好一些,因?yàn)槟悴挥靡粚訉拥貙懼欣ㄌ?hào)和引號(hào),你會(huì)不會(huì)嗤之以鼻?

好,我們?cè)賮?lái)看看下面的情況:

d = {"a": {"b": None}}
print(d["a"]["b"]["c"])

遍歷到一個(gè) None 對(duì)象,你會(huì)收到下面的錯(cuò)誤:

Traceback (most recent call last):
  File "/Users/cxhuan/Documents/python_workspace/mypy/pmodules/pglom/glomstudy.py", line 10, in <module>
    print(d["a"]["b"]["c"])
TypeError: 'NoneType' object is not subscriptable

我們來(lái)看看 glom 的處理方式:

from glom import glom

d = {"a": {"b": None}}
print(glom(d, "a.b.c"))

同樣地,glom 不能把錯(cuò)誤的輸出成對(duì)的,你會(huì)得到以下錯(cuò)誤:

Traceback (most recent call last):
  File "/Users/cxhuan/Documents/python_workspace/mypy/pmodules/pglom/glomstudy.py", line 11, in <module>
    print(glom(d, "a.b.c"))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/glom/core.py", line 2181, in glom
    raise err
glom.core.PathAccessError: error raised while processing, details below.
 Target-spec trace (most recent last):
 - Target: {'a': {'b': None}}
 - Spec: 'a.b.c'glom.core.PathAccessError: could not access 'c', part 2 of Path('a', 'b', 'c'), got error: AttributeError("'NoneType' object has no attribute 'c'")

如果你仔細(xì)看報(bào)錯(cuò)內(nèi)容,你就會(huì)發(fā)現(xiàn)這報(bào)錯(cuò)內(nèi)容極其詳細(xì),一目了然,這對(duì)于找程序 bug 簡(jiǎn)直是神器!

復(fù)雜用法

剛才簡(jiǎn)單的例子,讓大家對(duì) glom 有了直觀的認(rèn)識(shí),接下來(lái)我們看看 glom 的 glom 方法的定義:

glom(target, spec, **kwargs)

我們看看參數(shù)的含義:

  • target:目標(biāo)數(shù)據(jù),可以是dict、list或者其他任何對(duì)象

  • spec:是我們希望輸出的內(nèi)容

下面我們來(lái)使用這個(gè)方法。

先看一個(gè)例子。我們有一個(gè) dict ,想要獲取出 所有 name 的值,我們可以通過(guò) glom 來(lái)實(shí)現(xiàn):

data = {"student": {"info": [{"name": "張三"}, {"name": "李四"}]}}
info = glom(data, ("student.info", ["name"]))
print(info) # ['張三', '李四']

如果用傳統(tǒng)方式的話,我們可能會(huì)需要遍歷才能獲取到,但是使用 glom ,我們只需要一行代碼就可以了,輸出是一個(gè)數(shù)組。

如果你不想輸出數(shù)組,而是想要一個(gè) dict 的話,那也是很簡(jiǎn)單的:

info = glom(data, {"info": ("student.info", ["name"])})print(info) # {'info': ['張三', '李四']

我們只需要將原來(lái)的數(shù)組賦值給一個(gè)字典來(lái)接收就好了。

搞定麻煩需求

假如我現(xiàn)在有兩組數(shù)據(jù),我要取出 name 的值:

data_1 = {"school": {"student": [{"name": "張三"}, {"name": "李四"}]}}
data_2 = {"school": {"teacher": [{"name": "王老師"}, {"name": "趙老師"}]}}

spec_1 = {"name": ("school.student", ["name"])}
spec_2 = {"name": ("school.teacher", ["name"])}print(glom(data_1, spec_1)) # {'name': ['張三', '李四']}print(glom(data_2, spec_2)) # {'name': ['王老師', '趙老師']}

我們通常是這么寫,對(duì)嗎?假如我們有好多組數(shù)據(jù),每組都是類似的取法呢?這時(shí)候我們就會(huì)想辦法避免一個(gè)個(gè)重復(fù)寫 N 行參數(shù)了,我們可以使用 Coalesce 方法:

data_1 = {"school": {"student": [{"name": "張三"}, {"name": "李四"}]}}
data_2 = {"school": {"teacher": [{"name": "王老師"}, {"name": "趙老師"}]}}

spec = {"name": (Coalesce("school.student", "school.teacher"), ["name"])}
 print(glom(data_1, spec)) # {'name': ['張三', '李四']}print(glom(data_2, spec)) # {'name': ['王老師', '趙老師']}

我們可以用 Coalesce 把多個(gè)需求聚合起來(lái),然后針對(duì)同一個(gè) spec 來(lái)取值就行了。

下面再來(lái)一個(gè)大殺器——取值計(jì)算。glom 還可以對(duì)取值進(jìn)行簡(jiǎn)單計(jì)算,我們來(lái)看例子:

data = {"school": {"student": [{"name": "張三", "age": 8}, {"name": "李四", "age": 10}]}}
spec = {"sum_age": ("school.student", ["age"], sum)}
print(glom(data, spec)) # {'sum_age': 18}

到此,關(guān)于“如何用Python處理數(shù)據(jù)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI