我有这样的数据
product_title variation type product_price attribute
0 Chauvet DJ [Black, White] [899.99, 949.99] ['<p>apple,banana<p>', '<p>yewllow,orange,blue</p>']
我期望的数据框架将看起来像这样
product_title variation type product_price attribute
Chauvet DJ Black 899.99 <p>apple,banana<p>
Chauvet DJ White 949.99 <p>yewllow,orange,blue</p>
我试过这个代码:
data["variation type"] = data["variation type"].apply(str).str.strip('[]').apply(str).str.replace("'","").apply(str).str.split(',')
data["product_price"] = data["product_price"].apply(str).str.strip('[]').apply(str).str.replace("'","").apply(str).str.split(',')
data["attribute"] = data["attribute"].apply(str).str.strip('[]').apply(str).str.replace("'","").apply(str).str.split(r",(?=')",expand=True)
data = data.explode(['variation type', 'product_price','attribute'])
得到这个错误:
ValueError: columns must have matching element counts
这应该是您需要得到您期望的结果:
data = {
'product_title' : ['Chauvet DJ '],
'variation_type' : [['Black', 'White']],
'product_price' : [[899.99, 949.99]],
'attribute' : ['[<p>apple,banana<p>, <p>yewllow,orange,blue</p>]']
}
df = pd.DataFrame(data)
df['attribute'] = df['attribute'].apply(lambda x : x.replace('[','')).apply(lambda x : x.replace(']','')).apply(lambda x : x.split(', ', 1))
df.set_index(['product_title']).apply(pd.Series.explode).reset_index()
你可以在这里读到更多:在pandas DataFrame中解嵌(爆炸)多个列表列的有效方法