0

I am working with a pandas dataframe, and want to multiply a selection of a specific column. I want to select all the values of col2 less than 5, and multiply them by 10. How do I do this (without using a for loop)?

df = pandas.DataFrame({'col1':[2,3,5,7], 'col2':[1,2,30,4]})
    col1   col2
0   2      1  
1   3      2
2   5      30
3   7      4

I tried the following code, but this did not result in the dataframe I want:

df['col2'] = df.col2[df['col2']<5]*10
    col1   col2
0   2      10.0 
1   3      20.0
2   5      NaN
3   7      40.0

With a for loop, I was able to multiply each value smaller than 5 by 10, but the data set i am working on is quite large, so I would rather not use a for loop.

count=0
for value in df.col2:
    if value < 5:
        df.col2[count]=df.col2[count]*10
        count+=1   

Does someone know how to do this?

Timo
  • 357
  • 1
  • 10

1 Answers1

1

I managed to do this with Lambda expression:

df["col2"] = df["col2"].apply(lambda x:x*10 if x < 5 else x)

I assumed that numbers larger than 10 stay unchanged

Guy_g23
  • 316
  • 2
  • 7