按照下面的示例,我需要让我的代码忽略第一次匹配时间序列数据后的np.where。
因此,在2014-03-04 14:00:00
行上,np.where在test_output列上给出了1.0,并且正如预期的那样,在下一行上也给出了1.0。我只希望这一次触发一次。我将在问题的末尾显示所需的输出。
感谢您查看问题。
测试生成的数据帧:
df = pd.DataFrame(index=pd.date_range(start='2014-03-04 09:00:00', end='2014-03-04 16:15:00', freq='1h') + pd.date_range(start='2014-03-05 09:00:00', end='2014-03-05 16:15:00', freq='1h'), data={'test_1': np.nan})
df['test_1'][5:16]=1.0
df['test_output'] = np.where(df['test_1'] == 1.0,1.0,np.nan);
df
test_1 test_output
2014-03-04 09:00:00 NaN NaN
2014-03-04 10:00:00 NaN NaN
2014-03-04 11:00:00 NaN NaN
2014-03-04 12:00:00 NaN NaN
2014-03-04 13:00:00 NaN NaN
2014-03-04 14:00:00 1.0 1.0
2014-03-04 15:00:00 NaN NaN
2014-03-04 16:00:00 1.0 1.0
2014-03-05 09:00:00 1.0 1.0
这是所需的输出:
test_1 test_output
2014-03-04 09:00:00 NaN NaN
2014-03-04 10:00:00 NaN NaN
2014-03-04 11:00:00 NaN NaN
2014-03-04 12:00:00 NaN NaN
2014-03-04 13:00:00 NaN NaN
2014-03-04 14:00:00 1.0 1.0
2014-03-04 15:00:00 NaN NaN
2014-03-04 16:00:00 1.0 NaN
2014-03-05 09:00:00 1.0 NaN
最佳答案
使用遮罩上的first_valid_index
设置第一行:
In [30]:
df.loc[df[df['test_1'] == 1.0].first_valid_index(),'test_output'] = 1.0
df
Out[30]:
test_1 test_output
2014-03-04 09:00:00 NaN NaN
2014-03-04 10:00:00 NaN NaN
2014-03-04 11:00:00 NaN NaN
2014-03-04 12:00:00 NaN NaN
2014-03-04 13:00:00 NaN NaN
2014-03-04 14:00:00 1.0 1.0
2014-03-04 15:00:00 1.0 NaN
2014-03-04 16:00:00 1.0 NaN
2014-03-05 09:00:00 1.0 NaN
2014-03-05 10:00:00 1.0 NaN
2014-03-05 11:00:00 1.0 NaN
2014-03-05 12:00:00 1.0 NaN
2014-03-05 13:00:00 1.0 NaN
2014-03-05 14:00:00 1.0 NaN
2014-03-05 15:00:00 1.0 NaN
2014-03-05 16:00:00 1.0 NaN
分解以上内容:
In [32]:
df['test_1'] == 1.0
Out[32]:
2014-03-04 09:00:00 False
2014-03-04 10:00:00 False
2014-03-04 11:00:00 False
2014-03-04 12:00:00 False
2014-03-04 13:00:00 False
2014-03-04 14:00:00 True
2014-03-04 15:00:00 True
2014-03-04 16:00:00 True
2014-03-05 09:00:00 True
2014-03-05 10:00:00 True
2014-03-05 11:00:00 True
2014-03-05 12:00:00 True
2014-03-05 13:00:00 True
2014-03-05 14:00:00 True
2014-03-05 15:00:00 True
2014-03-05 16:00:00 True
Freq: BH, Name: test_1, dtype: bool
In [33]:
df[df['test_1'] == 1.0].first_valid_index()
Out[33]:
Timestamp('2014-03-04 14:00:00', offset='BH')
您可以使用
np.where
通过再次屏蔽df来做到这一点,以便通过将np数组与1.0进行比较来生成条件为假的NaN
:In [41]:
df.loc[df[np.where(df['test_1'] == 1.0, 1.0, 0) == 1].first_valid_index(), 'test_output'] = 1.0
df
Out[41]:
test_1 test_output
2014-03-04 09:00:00 NaN NaN
2014-03-04 10:00:00 NaN NaN
2014-03-04 11:00:00 NaN NaN
2014-03-04 12:00:00 NaN NaN
2014-03-04 13:00:00 NaN NaN
2014-03-04 14:00:00 1.0 1.0
2014-03-04 15:00:00 1.0 NaN
2014-03-04 16:00:00 1.0 NaN
2014-03-05 09:00:00 1.0 NaN
2014-03-05 10:00:00 1.0 NaN
2014-03-05 11:00:00 1.0 NaN
2014-03-05 12:00:00 1.0 NaN
2014-03-05 13:00:00 1.0 NaN
2014-03-05 14:00:00 1.0 NaN
2014-03-05 15:00:00 1.0 NaN
2014-03-05 16:00:00 1.0 NaN
关于python - 第一次匹配 Pandas 时间序列数据后忽略np.where,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38183182/