Search code examples
pythonpandasdataframeiterationdata-extraction

Pandas DataFrame -Extraction rows by using iterative condition


I have probably simple but for me tough question.

So, I have data like below:

table = pd.DataFrame([['AAA', 12333.21, 'buy'], ['BBB', 7683.15, 'buy'], ['AAA', 33.2, 'sell'], ['CCC', 33.2, 'buy']], columns=['Ticker', 'Value', 'Buy or Sell'])

and I would like to check in column 'Buy or Sell' which instruments are sold. Extract the "Ticker" for these instruments and create a new Data Frame containing only the instruments for this specific ticker. For above example it is:

Ticker Value Buy or Sell
AAA 12333.21 buy
AAA 33.2 sell

I started with following code:

marker = table[table["Buy or Sell"]=="sell"]
marker_final = marker.loc[:,"Ticker"]

But after that whenever I continue it does not work for example:

table[table["Ticker"] == marker_final]

Solution

  • You can subset table by all of the unique values in the 'Ticker' column of marker:

    marker_final = table[table['Ticker'].isin(marker['Ticker'].unique())]
    

    Result:

      Ticker     Value Buy or Sell
    0    AAA  12333.21         buy
    2    AAA     33.20        sell