當我的行中有空串列時,我收到此錯誤:
ValueError: columns must have matching element counts
這是我的資料框:
product title variation_list
Chauvet DJ GigBar Move Effect Light System ['Black', 'White']
Pioneer DJ DJM-S11 Professional DJ Mixer []
DJM-S11 Professional DJ []
Pioneer DJ ['black']
dj ['white','blue','red']
當我洗掉空串列行時,錯誤消失了。如何克服它?
這是我的代碼:
df[['variation_list']] = df[['variation_list']].applymap(lambda x: eval(x, {'nan': np.nan}))
df = df.explode(['variation_list'])
uj5u.com熱心網友回復:
使用 any() 檢查串列是否為空。如果串列為空,則回傳 False,否則回傳 True。如果串列為空,則將其更改為無,否則將值保留為非空串列
df[['short_des_list']] = df[['short_des_list']].applymap(lambda x: None if any(eval(x)) == False else eval(x))
df[['variation_list']] = df[['variation_list']].applymap(lambda x: None if any(eval(x)) == False else eval(x))
df[['price_list']] = df[['price_list']].applymap(lambda x: None if any(eval(x)) == False else eval(x))
df[['main_image_list']] = df[['main_image_list']].applymap(lambda x: None if any(eval(x)) == False else eval(x))
df = df.explode(['variation_list','short_des_list','price_list','main_image_list'])
df
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485531.html
標籤:Python python-3.x 熊猫
