Home > Net >  Change value of column of Dataframe based on value of other column
Change value of column of Dataframe based on value of other column

Time:04-17

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.

CodePudding user response:

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

CodePudding user response:

Another potential option to add to the pile:

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