Pandas multiplying column values under condition

Viewed 3096

would appreciate help with this: I have clean float value in column (pandas DF), if this value is <1 (bad parsed data), i need to multiply it with Price value from another column (corresponding axis).

    Price    Comission
    10 000   0.1 
    50 000   5 000 
    75 000   0.5

I tried smth like this : (without succes)

for i in range (df.shape [0]): 
  if (df['Comission'].iloc(i)<1)&(df['Comission'].iloc(i)>0):
    df['Comission'].iloc(i)= df['Comission'].iloc(i)*df['Price'].iloc(i)

Is there a way to do the selection easier in Pandas and multiply under selection?

2 Answers

Here's a way to do that:

df = pd.DataFrame({"price": [10, 50, 75], "commision": [0.1, 5.0, 0.5]})
print(df)

==>
   price  commision
0     10        0.1
1     50        5.0
2     75        0.5


df.loc[df.commision < 1, "commision"] = df.commision * df.price
print(df)

==>
   price  commision
0     10        1.0
1     50        5.0
2     75       37.5

In addition to @Roy2012's answer (+1), here's another way to do it.

import pandas as pd
import numpy as np

df = pd.DataFrame({"Price": [10, 50, 75], "Commision": [0.1, 5.0, 0.5]})

df['Price'] = np.where(
    df['Price'] < 1,                # Condition (price < 1).
    df['Price'] * df['Comission'],  # What to assign to price when condition is true. 
    df['Price']                     # What to assign to price when condition is false.
)
Related