pandas 当我的行中有空列表时,explode 函数抛出错误
pandas explode function throwing error when I have empty list in my row
当我的行中有空列表时,出现此错误:
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'])
使用 any() 检查列表是否为空。如果列表为空,它将 return False,否则为 True。
如果列表为空,将其更改为 None,否则将值保留为 non-empty 列表
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
当我的行中有空列表时,出现此错误:
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'])
使用 any() 检查列表是否为空。如果列表为空,它将 return False,否则为 True。 如果列表为空,将其更改为 None,否则将值保留为 non-empty 列表
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