我有一个Date 列和一个Toggle 列,当太阳下山时它为True。 现在,我需要一个计算列来说明现在是晚上还是白天。
在 true 之前是白天,然后是晚上,直到 date 列发生变化。
我创建了一些代码,但我对它不满意,因为它效率低下(for 循环)。
for i in range(0, len(DF)):
j = DF.columns.get_loc('Toggle')
k = DF.columns.get_loc('Day/Night') # This is just a copy of the index which is datetime
l = DF.columns.get_loc('Date')
if DF.iat[i, j] == True:
DF['Day/Night'].values[i] = 'Night'
elif DF.iat[i - 1, k] == 'Night' and DF.iat[i, l] == DF.iat[i - 1, l]:
DF['Day/Night'].values[i] = 'Night'
else:
DF['Day/Night'].values[i] = 'Day'
Date,Toggle
11/11/2018,FALSE
11/11/2018,FALSE
11/11/2018,TRUE
11/11/2018,FALSE
11/11/2018,FALSE
11/11/2018,FALSE
11/12/2018,FALSE
11/12/2018,FALSE
11/12/2018,FALSE
11/12/2018,TRUE
11/12/2018,FALSE
请您参考如下方法:
使用groupby + numpy.where :
indicator = df.groupby('Date')['Toggle'].cumsum()
df['Day/Night'] = np.where(indicator, 'Night', 'Day')
print(df)
输出
Date Toggle Day/Night
0 2018-11-11 False Day
1 2018-11-11 False Day
2 2018-11-11 True Night
3 2018-11-11 False Night
4 2018-11-11 False Night
5 2018-11-11 False Night
6 2018-11-12 False Day
7 2018-11-12 False Day
8 2018-11-12 False Day
9 2018-11-12 True Night
10 2018-11-12 False Night
