jeudi 9 janvier 2020

How to conditionally fill new column using for loop in python? [duplicate]

This question already has an answer here:

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'

Aucun commentaire:

Enregistrer un commentaire