Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 225

Subset pandas dataframe based on first non zero occurrence

Here is the sample dataframe:-

    Trade_signal

2007-07-31      0.0
2007-08-31      0.0
2007-09-28      0.0
2007-10-31      0.0
2007-11-30      0.0
2007-12-31      0.0
2008-01-31      0.0
2008-02-29      0.0
2008-03-31      0.0
2008-04-30      0.0
2008-05-30      0.0
2008-06-30      0.0
2008-07-31     -1.0
2008-08-29      0.0
2008-09-30     -1.0
2008-10-31     -1.0
2008-11-28     -1.0
2008-12-31      0.0
2009-01-30     -1.0
2009-02-27     -1.0
2009-03-31      0.0
2009-04-30      0.0
2009-05-29      1.0
2009-06-30      1.0
2009-07-31      1.0
2009-08-31      1.0
2009-09-30      1.0
2009-10-30      0.0
2009-11-30      1.0
2009-12-31      1.0

1 represents buy and -1 represents sell. I want to subset the dataframe so that the new dataframe starts with first 1 occurrence. Expected Output:-

2009-05-29      1.0
2009-06-30      1.0
2009-07-31      1.0
2009-08-31      1.0
2009-09-30      1.0
2009-10-30      0.0
2009-11-30      1.0
2009-12-31      1.0

Please suggest the way forward. Apologies if this is a repeated question.

Upvotes: 0

Views: 33

Answers (1)

thushv89
thushv89

Reputation: 11333

Simply do. Here df[1] refers to the column containing buy/sell data.

new_df = df.iloc[df[df["Trade Signal"]==1].index[0]:,:]

Upvotes: 1

Related Questions