0

I want to add a new column and fill values based on condition.

df:
indicator, value, a, b
1, 20, 5, 3
0, 30, 6, 8
0, 70, 2, 2
1, 10, 3, 7

I want to add a new column (value_new) based on Indicator. If indicator == 1, value_new = a*b otherwise value_new = value.

df:
indicator, value, a, b, value_new
1, 20, 5, 3, 15
0, 30, 6, 8, 30
0, 70, 2, 2, 70
1, 10, 3, 7, 21

I have tried following:

value_new = []
for in in range(1, len(df)):
  if indicator[i] == 1:
    value_new.append(df['a'][i]*df['b'][i])
  else:
    value_new.append(df['value'][i])
df['value_new'] = value_new

Error: 'Length of values does not match length of index'

And I have also tried:

for in in range(1, len(df)):
  if indicator[i] == 1:
    df['value_new'][i] = df['a'][i]*df['b'][i]
  else:
    df['value_new'][i] = df['value'][i]

KeyError: 'value_new'

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91

1 Answers1

1

You can use np.where:

df['value_new'] = np.where(df['indicator'], df['a']*df['b'], df['value'])
print(df)

Prints:

   indicator  value  a  b  value_new
0          1     20  5  3         15
1          0     30  6  8         30
2          0     70  2  2         70
3          1     10  3  7         21
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Would you be able to keep the preceding code using this? – SublimizeD Jan 09 '20 at 21:12
  • 1
    Wouldn't this make the multiplication if `indicator` is any positive integer except 1 too? It's better to write the full condition `df['indicator'] == 1`. – emremrah Jan 09 '20 at 21:16