Ale*_*Ale 5 python series pandas
我有两个系列的bool数据,我想将它们组合成一个新的系列对象,但组合逻辑取决于"历史"(以前的值).
Series1主要包含False,但包含单个True值.Series2通常包含True或False值的句点 - 重复值的概率非常高.
在结果系列中,我需要两个bool值的周期,每当两者都为True时以True结尾开始,并在Series2中的部分结束时结束,即不再包含True.
例如
s1 s2 result
0 False False False
1 False True False
2 True True True
3 False True True
4 False True True
5 True False False
6 False False False
Run Code Online (Sandbox Code Playgroud)
在第2行中,结果切换为True并保持打开,直到Series2中的True-phase在第5行结束.
这是我到目前为止所提出的:
import pandas as pd
import numpy as np
x = pd.DataFrame()
x['s1'] = [False, False, True, False, False, True, False]
x['s2'] = [False, True, True, True, True, False, False]
x['start'] = (x['s1'] & x['s2']).replace(False, np.nan)
x['end'] = (~ (x['s2'].shift() & (~ x['s2']))).replace(True, np.nan)
x['result'] = x['start'].fillna(x['end']).fillna(method='ffill').fillna(0) > 0
x
Run Code Online (Sandbox Code Playgroud)
即使我的解决方案有效,我也有这样的印象:我认为实现这个目标太难了!?
有什么建议?
首先,我们确信当为 Falseresult时,总是 False s2;当 和 都为 True 时,总是s1True s2。这不依赖于以前的值:
x.loc[~x['s2'], 'result'] = False
x.loc[x['s1'] & x['s2'], 'result'] = True
Run Code Online (Sandbox Code Playgroud)
然后我们用“前向填充”填充 NA:
x['result'].fillna(method = 'ffill', inplace = True)
Run Code Online (Sandbox Code Playgroud)
如果列的开头还剩下一些 NA,我们将它们替换为 False:
x['result'].fillna(False, inplace = True)
Run Code Online (Sandbox Code Playgroud)