我的 csv 中有多個可變產品。假設我有一個產品,標題為“Car model145”和這個“Car model145”具有三種不同的價格和尺寸。現在我想用標題擴展價格和顏色行。這是我的資料框:
title price color image
0 Car model145 2,54.00,852.00,2532.00 black,white,blue car iamge url
#three different price
我在價格欄中也有問題。如何洗掉2之后的第一個逗號?所以我可以正確分割價格行。我也不想擴展影像行。結果將如下所示:
title price color image
0 Car model145 254.00 black car iamge url
1 Car model145 852.00 white
2 Car model145 2532.00 blue
uj5u.com熱心網友回復:
令人困惑的是額外的價格 ( 2,)。所有價格都有這個嗎?你首先需要擺脫它。
然后你可以簡單地apply str.split和explode:
(df.assign(price=df['price'].str.replace(',', '', 1)) # remove first comma
.apply(lambda s: s.str.split(',').explode())
.assign(image=lambda d: d['image'].mask(d['image'].duplicated(), ''))
.reset_index(drop=True)
# .to_csv('filename.csv') # uncomment to save output as csv
)
輸出:
title price color image
0 Car model145 254.00 black car iamge url
1 Car model145 852.00 white
2 Car model145 2532.00 blue
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312281.html
標籤:蟒蛇-3.x 熊猫 数据框 python-2.7 pandas-groupby
上一篇:熊貓爆炸功能無法正常作業
下一篇:Python用裝飾器替換方法
