0

I need to perform column operations in a Pandas dataframe based on conditions. something like:

divide 'colB' by 1000 IF 'colA' is 'KG' ELSE 'colB'

I have already tried a normal FOR loop to check each element but it takes time. I need a solution similar to what is discussed here but with an ELSE statement as well. Pandas mathmatical operation, conditional on column value

I need something like:

df['TON'] = df.loc[df.colA.eq('KG'), 'colB'].divide(1000) ELSE...

It should fill with original value in colB if colA is not 'KG'.

Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
Alih3d
  • 45
  • 3
  • link to the post I refer to above : https://stackoverflow.com/questions/51034307/pandas-mathmatical-operation-conditional-on-column-value – Alih3d Jul 25 '19 at 12:37
  • `df['TON'] = df.colB.where(df.colA.ne('KG'), df.colB.div(1000))` ..? – Chris Adams Jul 25 '19 at 12:47

1 Answers1

0

In addition to what Chris suggested in the comments, you can also do numpy.where:

import numpy as np

df['TON'] = np.where(df['ColA'] == 'KG', df['ColB']/1000, df['ColB']) 
Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73
  • Thank you @chris-a and Ankur. Both codes worked perfectly. Is there a way to do multi IF statements in one go or do I need to do nested `.where` statements? – Alih3d Jul 25 '19 at 15:25
  • Depending on the complexity and situation, I would do multi np.where statements, or nested np.where statements if there are not so many conditions. :) – Ankur Sinha Jul 25 '19 at 16:10