1

I have the following dataframe.

df

ID   Q_code    A_value   B_value   C_code  Score 
1    A_code     1         0         1        0.5
2    B_code     0         0         0        1
3    C_code     0         1         1        0
4    B_code     1         1         1        1

Based on ID and Q_code, for example under Q_code column for A_code and ID == 1 I would like to multiply, A_value X Score and update Score value. under Q_code column for B_code and ID == 2, I would like to multiply, B_value X Score and update Score value on that particular row. The same works for others.

ID   Q_code    A_value   B_value   C_code  Score 
1    A_code     1         0         1        0.5
2    B_code     0         0         0        0
3    C_code     0         1         1        0
4    B_code     1         1         1        1

I have tried this as follows but I would like to consider ID and Q_code

df['Score'] = df['A_value'] * df['Score']

Can any one help with this?

Hiwot
  • 568
  • 5
  • 18

1 Answers1

0

If I understood correctly you want to pick values according to Q_code column. In this case you can use this answer.

Data

import pandas as pd
data = {'ID': {0: 1, 1: 2, 2: 3, 3: 4},
 'Q_code': {0: 'A_code', 1: 'B_code', 2: 'C_code', 3: 'B_code'},
 'A_value': {0: 1, 1: 0, 2: 0, 3: 1},
 'B_value': {0: 0, 1: 0, 2: 1, 3: 1},
 'C_value': {0: 1, 1: 0, 2: 1, 3: 1},
 'Score': {0: 0.5, 1: 1.0, 2: 0.0, 3: 1.0}}

df = pd.DataFrame(data)

Use lookup to select the value from given column

df["new_value"] = df.lookup(
    df.index, 
    df["Q_code"].str.replace("code", "value"))

which returns

   ID  Q_code  A_value  B_value  C_value  Score  new_value
0   1  A_code        1        0        1    0.5          1
1   2  B_code        0        0        0    1.0          0
2   3  C_code        0        1        1    0.0          1
3   4  B_code        1        1        1    1.0          1

So now you just need to multiply df["Score"] * df["new_value"]

rpanai
  • 12,515
  • 2
  • 42
  • 64