Annalix
Annalix

Reputation: 480

For loop and Conditionals in pandas DataFrame

I have this DataFrame and I need to write a conditionals to extract only the starred Energy.

Energy  Time
0       80
0       82 
0       84
0       86
287**   88
287     90
287     91
287     92
0       94
0       96
0       98
302**   100
302     102
302     104
302     106
0       108
0       110 

The idea is to accepts Energy values when Energy(t)>0 & Energy(t-1)==0.

I tried creating a for loop

set_time=set(df.loc[:,'Time'])
list_time=list(set_time)
for t, time in enumerate(list_time):
     if df['Energy'][t] > 0 & df['Energy'][t-1]==0:
        print(df['Energy'],t)

But I get errors. Thanks a lot in advance

Upvotes: 0

Views: 93

Answers (1)

BENY
BENY

Reputation: 323226

There is one way

v=df.eq(0).Energy.cumsum()

df.groupby(df.eq(0).Energy.cumsum()).head(2).loc[df.groupby(v).Energy.filter(lambda x : x.ne(0).any()).index].dropna()

Out[1538]: 
    Energy   Time
3      0.0   86.0
4    287.0   88.0
10     0.0   98.0
11   302.0  100.0

Upvotes: 1

Related Questions