2 回答

TA貢獻1818條經驗 獲得超8個贊
當前提取 isbn 元數據的實現速度極其緩慢且效率低下。
如前所述,有 482,000 個唯一的 isbn 值,其數據被多次下載(例如,每列一次,因為當前編寫的代碼)
最好一次性下載所有元數據,然后從 中提取數據
dict
,作為單獨的操作。塊
try-except
用于捕獲無效 isbn 值的錯誤。返回一個空的
dict
, ,因為不能與或 一起使用。{}
pd.json_normalize
NaN
None
沒有必要對 isbn 列進行分塊。
pd.json_normalize
用于擴展dict
from 返回的值.meta
。用于
pandas.DataFrame.rename
重命名列和pandas.DataFrame.drop
刪除列。此實現將比當前實現快得多,并且對用于獲取元數據的 API 發出的請求要少得多。
要從 中提取值
lists
(例如'Authors'
列),請使用df_meta = df_meta.explode('Authors')
; 如果有多個作者,將為列表中的每一位附加作者創建一個新行。
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貢獻1805條經驗 獲得超10個贊
如果沒有看到代碼,很難回答,但是try/ except應該確實能夠處理這個問題。
我不是這里的專家,但看看這段代碼:
l = [0, 1, "a", 2, 3]
for item in l:
try:
print(item + 1)
except TypeError as e:
print(item, "is not integer")
如果你嘗試用字符串進行加法,Python 會討厭它并用TypeError. 因此,您捕獲了TypeErrorexcept 的使用,并可能報告有關它的一些內容。當我運行這段代碼時:
1
2
a is not integer # exception handled!
3
4
您應該能夠使用 處理異常except NotValidISBNError,然后報告您喜歡的任何元數據。
您可以通過異常處理變得更加復雜,但這是基本思想。
添加回答
舉報