2 回答
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
當(dāng)前提取 isbn 元數(shù)據(jù)的實(shí)現(xiàn)速度極其緩慢且效率低下。
如前所述,有 482,000 個(gè)唯一的 isbn 值,其數(shù)據(jù)被多次下載(例如,每列一次,因?yàn)楫?dāng)前編寫的代碼)
最好一次性下載所有元數(shù)據(jù),然后從 中提取數(shù)據(jù)
dict,作為單獨(dú)的操作。塊
try-except用于捕獲無效 isbn 值的錯(cuò)誤。返回一個(gè)空的
dict, ,因?yàn)椴荒芘c或 一起使用。{}pd.json_normalizeNaNNone沒有必要對 isbn 列進(jìn)行分塊。
pd.json_normalize用于擴(kuò)展dictfrom 返回的值.meta。用于
pandas.DataFrame.rename重命名列和pandas.DataFrame.drop刪除列。此實(shí)現(xiàn)將比當(dāng)前實(shí)現(xiàn)快得多,并且對用于獲取元數(shù)據(jù)的 API 發(fā)出的請求要少得多。
要從 中提取值
lists(例如'Authors'列),請使用df_meta = df_meta.explode('Authors'); 如果有多個(gè)作者,將為列表中的每一位附加作者創(chuàng)建一個(gè)新行。
import pandas as pd # version 1.1.3
import isbnlib # version 3.10.3
# sample dataframe
df = pd.DataFrame({'isbn': ['9780446310789', 'abc', '9781491962299', '9781449355722']})
# function with try-except, for invalid isbn values
def get_meta(col: pd.Series) -> dict:
try:
return isbnlib.meta(col)
except isbnlib.NotValidISBNError:
return {}
# get the meta data for each isbn or an empty dict
df['meta'] = df.isbn.apply(get_meta)
# df
isbn meta
0 9780446310789 {'ISBN-13': '9780446310789', 'Title': 'To Kill A Mockingbird', 'Authors': ['Harper Lee'], 'Publisher': 'Grand Central Publishing', 'Year': '1988', 'Language': 'en'}
1 abc {}
2 9781491962299 {'ISBN-13': '9781491962299', 'Title': 'Hands-On Machine Learning With Scikit-Learn And TensorFlow - Techniques And Tools To Build Learning Machines', 'Authors': ['Aurélien Géron'], 'Publisher': "O'Reilly Media", 'Year': '2017', 'Language': 'en'}
3 9781449355722 {'ISBN-13': '9781449355722', 'Title': 'Learning Python', 'Authors': ['Mark Lutz'], 'Publisher': '', 'Year': '2013', 'Language': 'en'}
# extract all the dicts in the meta column
df = df.join(pd.json_normalize(df.meta)).drop(columns=['meta'])
# extract values from the lists in the Authors column
df = df.explode('Authors')
# df
isbn ISBN-13 Title Authors Publisher Year Language
0 9780446310789 9780446310789 To Kill A Mockingbird Harper Lee Grand Central Publishing 1988 en
1 abc NaN NaN NaN NaN NaN NaN
2 9781491962299 9781491962299 Hands-On Machine Learning With Scikit-Learn And TensorFlow - Techniques And Tools To Build Learning Machines Aurélien Géron OReilly Media 2017 en
3 9781449355722 9781449355722
TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
如果沒有看到代碼,很難回答,但是try/ except應(yīng)該確實(shí)能夠處理這個(gè)問題。
我不是這里的專家,但看看這段代碼:
l = [0, 1, "a", 2, 3]
for item in l:
try:
print(item + 1)
except TypeError as e:
print(item, "is not integer")
如果你嘗試用字符串進(jìn)行加法,Python 會(huì)討厭它并用TypeError. 因此,您捕獲了TypeErrorexcept 的使用,并可能報(bào)告有關(guān)它的一些內(nèi)容。當(dāng)我運(yùn)行這段代碼時(shí):
1
2
a is not integer # exception handled!
3
4
您應(yīng)該能夠使用 處理異常except NotValidISBNError,然后報(bào)告您喜歡的任何元數(shù)據(jù)。
您可以通過異常處理變得更加復(fù)雜,但這是基本思想。
添加回答
舉報(bào)
