'Using if else in python to determine whether or not to perform an operation on another cell in the same row

This should be easy for anyone good at coding I am just learning and struggling with syntax. I have a data frame with 9 columns, 2 of these are 'Account Name'and 'Amount'I just want to say that if the 'Account Name' is 'CREDIT CARD' I want it to divide the value in 'Amount' by 2.

The data type for 'Account Name' is object and for 'Amount' is float 64.

Here is what I have

df.loc[df['Account Name'] == 'CREDIT CARD', 'Adjusted Amount'] = df['Amount']/2

I know this is creating a new column but I wasn't able to make it work in place either.



Solution 1:[1]

You are close, need assign output to same column Amount:

#thanks Corralien
df.loc[df['Account Name'] == 'CREDIT CARD', 'Amount'] /= 2

#working same like
df.loc[df['Account Name'] == 'CREDIT CARD', 'Amount'] = df['Amount']/2

Or if need new column use numpy.where:

df['Adjusted Amount'] = np.where(df['Account Name'] == 'CREDIT CARD',
                                 df['Amount']/2, 
                                 df['Amount'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1