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

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


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

>Solution :

IIUC, try:

df["price"] = df["product_name"].where(df["price"].eq(".")).fillna(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"])
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