'Change value of column of Dataframe based on value of other column

I have a dataframe listing insider trades, which looks like this :

    Transaction Transaction Date Transaction Total
0   Sell          2022-02-28             66048.0
1   Sell          2022-02-24              8000.0
2   Buy           2022-02-24              8000.0
3   Sell          2022-02-03           4369548.0

I now want to multiply the value of Transaction Total based on the Transaction column, e.g if the Transaction column is Sell, multiply the value in the Transaction Total by -1.

Ive tried adding a new column with np.where and then multiply this column with the Transaction total column:

df['BuySell'] = np.where((df["Transaction"] =="Sell") or (df[Transaction]=="Sall"), -1, 1 )

This didnt work and seemed inefficient.



Solution 1:[1]

You can opt for in place modification using boolean indexing:

df.loc[df['Transaction'].eq('Sell'), 'Transaction Total'] *= -1

output:

  Transaction Transaction Date  Transaction Total
0        Sell       2022-02-28           -66048.0
1        Sell       2022-02-24            -8000.0
2         Buy       2022-02-24             8000.0
3        Sell       2022-02-03         -4369548.0

You command could be fixed using:

df['BuySell'] = np.where(df["Transaction"].isin(['Sell', 'Sall']),
                         -df['Transaction Total'], df['Transaction Total'])

output:

  Transaction Transaction Date  Transaction Total    BuySell
0        Sell       2022-02-28            66048.0   -66048.0
1        Sell       2022-02-24             8000.0    -8000.0
2         Buy       2022-02-24             8000.0     8000.0
3        Sell       2022-02-03          4369548.0 -4369548.0

Solution 2:[2]

You can try df.mask

df['Transaction Total'].mask(df['Transaction'].eq('Sell'), -df['Transaction Total'], inplace=True)
0        Sell       2022-02-28           -66048.0
1        Sell       2022-02-24            -8000.0
2         Buy       2022-02-24             8000.0
3        Sell       2022-02-03         -4369548.0

Solution 3:[3]

df.loc[df["Transaction"] == "Sell", "Transaction Total"] = -df['Transaction Total']

Solution 4:[4]

Another potential option to add to the pile:

df["buysell"] = df["Transaction Total"] * df.Transaction.map({"Sell":-1, "Buy":1})

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 mozway
Solution 2 Ynjxsjmh
Solution 3 Subhash Tulsyan
Solution 4 chase