Search code examples
pythonpandasmultiplication

Multiplying a df column by a value, based on the columns values


My problem is this: I've got a column, where some numbers should be multiplied by 1,000. Let's say:

  • 1 5345
  • 2 1023
  • 3 1.6
  • 4 4325
  • 5 2.5

How can I multiply this column by a thousand but only for the numbers 1.6 and 2.5? I can think of the condition (would be something like <1,000 as all the other numbers in the columns are above 1,000), but I'm not sure what approach is best.

Thanks!

P.S. I'm not gonna state the obvious, I've tried df[series] = df[series]*1000 but that multiplied the entire column by 1,000, not just the numbers I want.


Solution

  • Use DataFrame.loc with condition - here Series.lt:

    df.loc[df['col'].lt(1000), 'col'] *= 1000
    
    #working like
    #df.loc[df['col'].lt(1000), 'col'] = df.loc[df['col'].lt(1000), 'col'] * 1000
    print (df)
          col
    1  5345.0
    2  1023.0
    3  1600.0
    4  4325.0
    5  2500.0