dimanche 16 juin 2019

How do I apply an if...else clause to an entire column in Python3?

I'd like to take a set of values in a df column, and apply a correction factor depending on the value of a separate column. I would like to run an if...else clause which adds a different amount depending on the value in the first column.

I've tried the following:

if df['A'] > 5:
    df['B'] = df['B']+2
else df['B']=df['B']-2

I would expect the rows in column A which are larger than 5 to have 2 added to them in column B, and those which aren't to have 2 taken from them. Instead I get an error message saying that the truth value of a series is ambiguous. I guess this is fairly basic, but the answers I've found on Stackoverflow all seem to relate to a different programming language.

Aucun commentaire:

Enregistrer un commentaire