我的目標是創建一個基于“viewCount”、“likeCount”、“favoriteCount”和“commentCount”的資料框。
下面的代碼為“viewCount”、“favoriteCount”和“commentCount”提供了 25 個值,但“likeCount”出現錯誤,因為“likeCount”串列中有 1 個缺失值。
當程式看到該值不存在時,如何創建一個“if, then 陳述句”將 0 計數放入“likeCount”串列中。
下面的 if then 陳述句是我嘗試過的,但我得到一個 KeyError: 'likeCount' 錯誤
x=0
y=0
viewCount = []
likeCount = []
favoriteCount = []
commentCount = []
while (x < len(response2)):
viewCount.append(response2[x]['items'][0]['statistics']['viewCount'])
favoriteCount.append(response2[x]['items'][0]['statistics']['favoriteCount'])
commentCount.append(response2[x]['items'][0]['statistics']['commentCount'])
if not (response2[x]['items'][0]['statistics']['likeCount']):
likeCount.append(0)
else:
likeCount.append(response2[x]['items'][0]['statistics']['likeCount'])
x=x 1
#print(video_title, video_id)
df2 = pd.DataFrame({'viewCount': viewCount,'favoriteCount': favoriteCount,
'commentCount': commentCount, 'likeCount' : likeCount} )
df2
錯誤資訊:
KeyError Traceback (most recent call last)
10 favoriteCount.append(response2[x]['items'][0]['statistics']['favoriteCount'])
11 commentCount.append(response2[x]['items'][0]['statistics']['commentCount'])
---> 12 if not (response2[x]['items'][0]['statistics']['likeCount']):
13 likeCount.append(0)
14 else:
KeyError: 'likeCount'
uj5u.com熱心網友回復:
似乎response2沒有正確的鍵值對。也許您可以嘗試使用受控例外。
例如:
try:
likeCount.append(response2[x]['items'][0]['statistics']['likeCount'])
except:
likeCount.append(0)
另外,我強烈建議使用snake_case 而不是camelCase 來命名變數。在 python 中,snake_case 通常用于函式和變數,而 camelCase 是為類保留的。
希望我的回答對你有所幫助。
uj5u.com熱心網友回復:
很難確定,但您可能會收到錯誤訊息,因為使用 ['likeCount'] 假定物件中存在索引。這是一個不同的寫法:
if not (response2[x]['items'][0]['statistics']['likeCount']):
likeCount.append(0)
else:
likeCount.append(response2[x]['items'][0]['statistics']['likeCount'])
所以它應該作業:
likeCount.append(response2[x]['items'][0]['statistics'].get('likeCount', 0))
這利用了 get 函式(如果找不到索引,它不會出錯)并將默認值設定為 0。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/417256.html
標籤:
上一篇:回圈困境,不同的方法相同的結果
