遍历列表和自动算法的问题

时间:2020-10-17 13:05:00

标签: python pandas dataframe for-loop

参考以下代码,我是否可以自动循环遍历open_count和close_count以创建trips_check?每当添加新变量时,我一直手动在Trip_check中键入变量“ Open_1”,“ Close_1” ...,但我发现这样做效率不高。

door_dur_log = pd.DataFrame([[1, 2.029, 2.208, np.nan, np.nan, 3.01, np.nan, np.nan],
[2, 2.029, 2.208, np.nan, np.nan, 3.01, 2.42, np.nan],
[3, 1.266, np.nan, np.nan, np.nan, 3.846, np.nan, np.nan],
[4, 1.266, 2.224, np.nan, np.nan, 3.846, 3.102, np.nan],
[5, 3.102, 2.923, 3.156, np.nan, 1.318, 2.186, np.nan],
[6, 2.156, np.nan, np.nan, np.nan, 3.039, np.nan, np.nan],
[7, 2.13, 2.195, np.nan, np.nan, 2.982, 2.817, np.nan],
[8, 2.552, np.nan, np.nan, np.nan, 2.408, np.nan, np.nan]], columns = ['Trip', 'Open_1', 'Open_2', 'Open_3', 'Open_4', 'Close_1', 'Close_2', 'Close_3'])

open_count = ['Open_1', 'Open_2', 'Open_3', 'Open_4']
close_count = ['Close_1', 'Close_2', 'Close_3']

trips_check = door_dur_log[(door_dur_log['Open_1'] > 2.75)|(door_dur_log['Open_1'] < 1) | 
                           (door_dur_log['Open_2'] > 2.75)|(door_dur_log['Open_2'] < 1) | 
                           (door_dur_log['Open_3'] > 2.75)|(door_dur_log['Open_3'] < 1) |
                           (door_dur_log['Open_4'] > 2.75)|(door_dur_log['Open_4'] < 1) |
                           (door_dur_log['Close_1'] > 2.75)|(door_dur_log['Close_1'] < 1)|
                           (door_dur_log['Close_2'] > 2.75)|(door_dur_log['Close_2'] < 1)|
                           (door_dur_log['Close_3'] > 2.75)|(door_dur_log['Close_2'] < 1)]

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作

from functools import reduce

lb_open = [door_dur_log[_] > 2.75 for _ in open_count]
lb_close = [door_dur_log[_] > 2.75 for _ in close_count]
ub_open = [door_dur_log[_] < 1 for _ in open_count]
ub_close = [door_dur_log[_] < 1 for _ in close_count]

constraints = [*lb_open, *lb_close, *ub_open, *ub_close]
combined = reduce(lambda a, b : a|b, constraints)

trips_check = door_dur_log[combined]

前4行在list comprehension之前。

*运算符将列表解压缩。它可以用来合并不同的列表。例如,

a = [1,2,3]
b = [4,5,5]
c = [*a, *b] # c = [1,2,3,4,5,5]

最后,reduce操作采用二进制操作并通过将运算应用于到目前为止累积的结果以及列表中的下一个元素来累积结果。例如,

a = reduce(lambda x, y : x + y, [1,2,3,4]) # a = 10

可以找到更多信息here