Pandas爆炸功能无法正常工作

2024-04-29 22:06:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的数据框:

     title            price        weight
   0 Crloni Model145  $45,$50,$60  200gm,500gm,800gm

这里,200克45美元,500克50美元,800克60美元。我预期的数据框架如下:

    title              price      weight
    0 Crloni Model145  $45        200gm 
    1 Crloni Model145  $50        500gm
    2 Crloni Model145  $60        800gm
   

但现在我得到了这样的数据帧

       title           price      weight
    0 Crloni Model145  $45        200gm 
    1 Crloni Model145  $45        500gm
    2 Crloni Model145  $45        800gm
    3 Crloni Model145  $50        200gm 
    4 Crloni Model145  $50        500gm
    5 Crloni Model145  $50        800gm
    6 Crloni Model145  $45        200gm 
    7 Crloni Model145  $45        500gm
    8 Crloni Model145  $45        800gm
    9 Crloni Model145  $60        200gm 
    10 Crloni Model145  $60        500gm
    11 Crloni Model145  $60        800gm

这是我的密码:

data['price']=data['price'].str.split(',')
data = data.explode('price')
data['weight']=data['weight'].str.split(',')
data = data.explode('weight')

更新问题:

我申请了蜥蜴比尔的解决方案。我没有得到任何错误,但我没有看到任何价格,重量在我的csv时,导出csv文件

data['price']=data['price'].str.split(',')
data['weight']=df['weight'].str.split(',')
data = data.set_index(['title']).apply(pd.Series.explode).reset_index()

data.to_csv('...mypath/data.csv')

见图片: enter image description here

这是BENY的解决方案,但我得到了cannot reindex from a duplicate axis

data['price'] = data['price'].str.split(',')
data['weight'] = data['weight'].str.split(',')
out = data.explode(['price','weight'])
data['description'] = data['description'].mask(data['description].shift() == data['description'])

#更新2

蜥蜴比尔解决方案起作用了,但我不明白为什么贝尼解决方案不起作用?为什么我在应用BENY解决方案时会出现cannot reindex from a duplicate axis此错误

更新3 我的原始excel文件的几行

     category     title       price     weight             description
       Shirt    men-shirt    20,25,35    100gm,50gm,150gm   shirt description....   
      pant    men-pent    40,35,90    200gm,350gm,150gm   pant description....   

Tags: csv数据datatitle错误description解决方案price
2条回答

如果您有1.3.0之前的Pandas版本,其中添加了多列explode

由于拆分字符串后的列表具有相同数量的元素,因此可以将Series.explode应用于price列和weight列,以获得预期的输出

import pandas as pd

df = pd.DataFrame({'title': ['Crloni Model145'],
                   'price': ['$45,$50,$60'],
                   'weight': ['200gm,500gm,800gm']})

df['price']=df['price'].str.split(',')
df['weight']=df['weight'].str.split(',')

df = df.set_index(['title']).apply(pd.Series.explode).reset_index()

print(df)

我将索引设置为title,因为我不希望explode应用于该列,然后在末尾重置索引,以便title再次成为一个常规列

输出:

             title price weight
0  Crloni Model145   $45  200gm
1  Crloni Model145   $50  500gm
2  Crloni Model145   $60  800gm

更新你的pandasexplode现在可以接受两列

df['price'] = df['price'].str.split(',')
df['weight'] = df['weight'].str.split(',')
out = df.explode(['price','weight'])

相关问题 更多 >