将两个Pandas系列合并,改变逻辑。

5
我有两组布尔数据,想将它们组合成一个新的序列对象,但是组合逻辑取决于“历史”(先前的值)。
Series1大多包含False,但也有单个True值。 Series2通常包含True或False值的周期性 - 重复值的概率相当高。
在结果序列中,当两者都为True时,我需要以True-section开头的bool值段,并在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

在第2行,结果变为True并保持不变,直到Series2的True阶段在第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

虽然我的解决方案有效,但我觉得我可能想得太复杂了!?
您有什么建议吗?
1个回答

1
首先,我们确定当s2为False时,result始终为False;当s1s2都为True时,result始终为True。这并不取决于先前的值:
x.loc[~x['s2'], 'result'] = False
x.loc[x['s1'] & x['s2'], 'result'] = True

然后我们使用“向前填充”的方法来填充NA值:
x['result'].fillna(method = 'ffill', inplace = True)

如果在列的开头还有一些NA值,我们将它们替换为False:

x['result'].fillna(False, inplace = True)

这对我来说看起来不错。顺便说一句,更紧凑的方法来完成前两行是:x.loc[x.s1 | ~x.s2,'s3'] = x.s2 - JohnE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接