循环以查找数字不等于零的范围

2024-05-16 21:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个循环来找出数字不等于0时的范围

让我向您展示示例数据

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

正如您所看到的上述示例代码,如何使其返回数字不等于0的范围

期望输出:

Window No. 1 ~ Window No.4
Window No. 7 ~ Window No.9

Tags: 数据no代码示例index数字windowfuel
1条回答
网友
1楼 · 发布于 2024-05-16 21:19:20

另一种选择:

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

相关问题 更多 >