Reputation: 69
I'm trying to write a loop to find out the range when the numbers does not equal to 0.
Let me show you sample data
index Window No. Fuel Consumption
0 0 0
1 1 100
2 2 101.1
3 3 102.2
4 4 107.5
5 5 0
6 6 0
7 7 100
8 8 110
9 9 107.5
10 10 0
11 11 0
As you can see the above sample code, how do I make it return me the ranges where numbers does not equal to 0?
Desired output:
Window No. 1 ~ Window No.4
Window No. 7 ~ Window No.9
Upvotes: 0
Views: 368
Reputation: 215047
Another option:
import numpy as np
zero = df['Fuel Consumption'] == 0
nonzero = df['Fuel Consumption'] != 0
# find start indices of all non zero sequences
start = np.flatnonzero(nonzero & zero.shift(fill_value=True))
# find end indices of all non zero sequences
end = np.flatnonzero(nonzero & zero.shift(-1, fill_value=True))
# loop through indices and print Window No.
windows = df['Window No.'].values
for i in range(len(start)):
ws, we = windows[start[i]], windows[end[i]]
avg_fuel = df['Fuel Consumption'].iloc[start[i]:end[i]+1].mean()
print(f'Window No. {ws} ~ Window No. {we} with avg fuel: {avg_fuel:.2f}')
Window No. 1 ~ Window No. 4 with avg fuel: 102.70
Window No. 7 ~ Window No. 9 with avg fuel: 105.83
Upvotes: 1