pandas 如何将可变产品的一行拆分为多行?
pandas how to split one row to multiple row for variable product?
我的 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
令人困惑的是额外价格 (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
我的 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
令人困惑的是额外价格 (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