0
$\begingroup$

How to replace a part string value of a column using another column.

My DataSet here is :

ID          Product Name                            Size ID    Size Name
1   24 Mantra Ancient Grains Foxtail Millet 500 gm      1       500 gm
2   24 Mantra Ancient Grains Little Millet 500 gm       2       500 gm
3   24 Mantra Naturals Almonds 100 gm                   3       100 gm
4   24 Mantra Naturals Kismis 100 gm                    4       100 gm
5   24 Mantra Organic Ajwain 100 gm                     5       100 gm
6   24 Mantra Organic Apple Blast Drink 250 ml          6       250 ml
7   24 Mantra Organic Apple Juice 1 Ltr Tetra Pack      7       1000 ml
8   24 Mantra Organic Apple Juice 200 ml                8       200 ml
9   24 Mantra Organic Assam Tea 100 gm                  9       100 gm

Requirement here is the Product Name column value is 24 Mantra Ancient Grains Foxtail Millet 500 gm and the Size Name column has 500 Gm. In this case my output will be 24 Mantra Ancient Grains Foxtail Millet. If the Size Name contains in the Product Name string remove the size name word ignoring the case else no need to take any action.

$\endgroup$
  • $\begingroup$ What exactly are you asking? What's your expected output? $\endgroup$ – marco_gorelli Oct 8 '18 at 10:00
  • $\begingroup$ The "Product ID" Column value is [24 Mantra Ancient Grains Foxtail Millet 500 gm] and the "Size name" column have [500 Gm] In this case my output will be "24 Mantra Ancient Grains Foxtail Millet" $\endgroup$ – sanjaya panigrahy Oct 9 '18 at 17:15
2
$\begingroup$
data['Product Name'] = data['Product Name'].str.replace('\d+','')

This should get rid of the number if that's what you are looking for. I am not sure what you mean by 'chomped.'

$\endgroup$
1
$\begingroup$

Try this

data['Product Name'] = data['Product Name'].apply(lambda x: re.sub(data.loc[data['Product Name'] == x, 'Size Name'].values[0], '', x))
$\endgroup$
1
$\begingroup$

This should help.

import pandas as pd
Product_Name = ["24 Mantra Ancient Grains Foxtail Millet 500 gm",
                "24 Mantra Ancient Grains Little Millet 500 gm",
                "24 Mantra Naturals Almonds 100 gm",
                "24 Mantra Naturals Kismis 100 gm",
                "24 Mantra Organic Ajwain 100 gm"]

Size_Name = ["500 gm", "500 gm", "100 gm", "100 gm", "100 gm"]

data = pd.DataFrame(
        {'Product_Name': Product_Name,
         'Size_Name': Size_Name 
        })

# Remove characters from one column based on string of another column
data['Product_Name'] = data['Product_Name'].replace(data['Size_Name'],'', regex = True)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.