0

I'm trying to turn the numbers (in "sharesTraded" column) negative based on the condition that they are sells, not buys. Here is the pandas series:

    lastDate    transactionType sharesTraded
0   2022Q4  Sell    20200
1   2022Q4  Automatic Sell  176299
2   2022Q4  Automatic Sell  8053
7   2022Q4  Automatic Sell  167889
8   2022Q4  Sell    13250
9   2022Q4  Automatic Sell  176299
18  2022Q3  Automatic Sell  96735
19  2022Q3  Automatic Sell  15366
22  2022Q3  Automatic Sell  25000
24  2022Q2  Automatic Sell  25000
25  2022Q2  Automatic Sell  8000
30  2022Q2  Automatic Sell  29198
31  2022Q2  Automatic Sell  105901
40  2022Q1  Automatic Sell  25000
45  2022Q1  Sell    1986

My code is an attempt of trying to create a for loop to check if the "transactionType" column has "sell" or "automatic sell" and then turn the integer into a negative:

import json
import pandas as pd 

data = json.load(open("AAPL22_trades.json"))

df = pd.DataFrame.from_dict(data)

for x in df['transactionType']:
    if df['transactionType'].item() == 'Sell':
        df['sharesTraded'].replace('-', '')
for x in df['transactionType']:
    if df['transactionType'].item() == 'Automatic Sell':
        df['sharesTraded'].replace('-', '')

Although all the data are sells, I need the condition in my code incase buys show up, so it's not preferable to generally turn ALL integers negative. I'm not trying to put the data back into the json, I need the data for other operations. It's just turning the integers to negative numbers I can't seem to do.

  • `df.loc[df['sharesTraded'].eq('Sell'), 'sharesTraded'] *= -1` – mozway Dec 05 '22 at 10:24
  • How would i assign it to a variable? Say if I wanted to to do "df2 = df.loc[df['sharesTraded'].eq('Sell'), 'sharesTraded'] *= -1" @mozway – kiestuthridge23 Dec 05 '22 at 10:28
  • `df2 = df.copy() ; df2.loc[df2['sharesTraded'].eq('Sell'), 'sharesTraded'] *= -1` or `df2 = df.assign(sharesTraded=np.where(df2['sharesTraded'].eq('Sell'), -df['sharesTraded'], df['sharesTraded']))` – mozway Dec 05 '22 at 10:30
  • 1
    use `apply` like this: `df["sharesTraded"] = df.apply(lambda x: -x["sharesTraded"] if x["transactionType"] == "Automatic Sell" or x["transactionType"] == "Sell" else x["sharesTraded"], axis=1)` – Amir nazary Dec 05 '22 at 10:46

0 Answers0