Home > Enterprise >  Muliply only numeric values from object type column pandas
Muliply only numeric values from object type column pandas

Time:02-23

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

CodePudding user response:

import pandas as pd    
df = pd.DataFrame({'col1': [1, 2.5, 4, 5.5, 'object']})
df["col1"].apply(lambda x: 5 * x if (isinstance(x, int) or isinstance(x, float)) else x)

CodePudding user response:

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
  • Related