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

Muliply only numeric values from object type column pandas

df = pd.DataFrame({'col1': [1, 2, 4, 5, 'object']})
df['col1'] * 5

this code multiplies ‘object’ string to 5 and writes the string 5 times but I want to multiply only numeric values strings should be leave as it is.
I have also tried to convert column to numeric using to_numeric with errors=’coerce’ it converts all string to nan

>Solution :

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

Use isnumeric to identify rows with numerics values.

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 4, 5, 'object']})

mask_ = df['col1'].astype(str).str.isnumeric()

df.loc[mask_, 'col1'] = df.loc[mask_, 'col1'] * 5

     col1
0       5
1      10
2      20
3      25
4  object
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