Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change pandas index value base on column condition

I want to change an index value for a specific column condition.

Here an example

import pandas as pd

data = {
    "Product": ["Computer", "Printer", "Monitor"],
    "Price": [120, 25, 40],
}

df = pd.DataFrame(data, index=["Item_1", "Item_1", "Item_1"])

        Product     Price
Item_1  Computer    120
Item_1  Printer     25
Item_1  Monitor     40

I want to modify the index value ‘Item_1’ to ‘TOTO’ for df.loc[df.Product==’Monitor’]
(and without passing by reset_index()).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The result should be:

        Product     Price
Item_1  Computer    120
Item_1  Printer     25
TOTO    Monitor     40

>Solution :

You can use np.where with mask:

df.index = np.where(df.Product == "Monitor", "TOTO", df.index)

print(df)

Prints:

         Product  Price
Item_1  Computer    120
Item_1   Printer     25
TOTO     Monitor     40
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading