Slartibartfast
Slartibartfast

Reputation: 1200

How to sum values in pandas based on bool condition

I have the following dataframe:

                   High          Low  ...    Adj Close    bcc
Date                                  ...                    
2018-01-02  2695.889893  2682.360107  ...  2695.810059  False
2018-01-03  2714.370117  2697.770020  ...  2713.060059  False
2018-01-04  2729.290039  2719.070068  ...  2723.989990  False
2018-01-05  2743.449951  2727.919922  ...  2743.149902  False
2018-01-08  2748.510010  2737.600098  ...  2747.709961   True
                ...          ...  ...          ...    ...
2020-04-09  2818.570068  2762.360107  ...  2789.820068  False
2020-04-13  2782.459961  2721.169922  ...  2761.629883  False
2020-04-14  2851.850098  2805.100098  ...  2846.060059  False
2020-04-15  2801.879883  2761.540039  ...  2783.360107  False
2020-04-16  2806.510010  2764.320068  ...  2778.219971  False

How can i add the next 3 values of column Low whenever bcc column is True and save this data into a different dataframe?

Upvotes: 0

Views: 385

Answers (1)

baby_yoda
baby_yoda

Reputation: 103

I am not sure of the efficiency of this code but you can try this :

match_idx = df.index[df.bcc == True].tolist()

next_three_rows_list = [list(range(idx+1,idx+4)) for idx in match_idx]
sums = []
for i in range(0,len(next_three_rows)):
    sums.append(df.loc[next_three_rows[i]].Low.sum())

new_df = pd.DataFrame(sums,columns=['sum'])

Upvotes: 1

Related Questions