Yun Tae Hwang
Yun Tae Hwang

Reputation: 1471

dataframe selecting rows with given conditions and operating

I have a dataframe looks like this:

 import pandas as pd    
    df = pd.DataFrame({'AA': [1, 1, 2, 2], 'BB': ['C', 'D', 'C', 'D'], 'CC': [10,20,30,40], 'DD':[], 'EE':[]})

Now, I want to multiply a value in the column 'CC' with number 2 if 'AA'= 1 and 'BB'='C'. For example, the first row will meet the conditions, so the value in the column 'CC,' which is 10 will be multiplied by 2 and the output will go to the same row in 'DD' column.

I will have other requirements for other pairs of 'AA' and 'BB,' but it will be a good start if I can get the idea of how to apply multiplication on rows that meet conditions.

Thank you so much.

Upvotes: 1

Views: 33

Answers (1)

piRSquared
piRSquared

Reputation: 294258

m0 = df.AA == 1
m1 = df.BB == "C"

df.loc[m0 & m1, "DD"] = df.loc[m0 & m1, "CC"] * 2

Upvotes: 2

Related Questions