'If a value of a column is a specific string, replace it with the value of another column

I have a column in a pandas data frame that some values are a dop ('.'). I want to replace these values with the value contained in another column.


data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
        'price': [1200, ., 300, 450, .]
        }

df = pd.DataFrame(data)

print (df)


  product_name  price
0       laptop   1200
1      printer    .
2       tablet    300
3         desk    450
4        chair    .


And the output I am trying to get should be

  product_name  price
0       laptop   1200
1      printer    printer
2       tablet    300
3         desk    450
4        chair    chair




Solution 1:[1]

IIUC, try:

df["price"] = df["product_name"].where(df["price"].eq("."), df["price"])

>>> df
  product_name    price
0       laptop     1200
1      printer  printer
2       tablet      300
3         desk      450
4        chair    chair

Or:

>>> pd.to_numeric(df["price"],errors="coerce").fillna(df["product_name"])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1