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()).
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