Home > Software engineering >  If a value of a column is a specific string, replace it with the value of another column
If a value of a column is a specific string, replace it with the value of another column

Time:04-14

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


CodePudding user response:

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"])
  • Related