检查前一个值条件,并使用条件抓取后继值

  • 本文关键字:条件 抓取 一个 python pandas
  • 更新时间 :
  • 英文 :


我有以下示例系列

s = {0: 'feedback ratings-positive-unexpected origin',
1: 'decision-tree identified-regex input',
2: 'feedback ratings-options input',
3: 'feedback ratings-options-unexpected origin',
4: 'checkout order-placed input',
5: 'decision-tree identified-regex input'}

我要做的是获取&;unexpected&;下面的值关键字字符串,并有"input"把它们串起来。例如,如果我有"反馈评级-正-意外来源",下一个值包含"输入";字符串。地图标记为"真"。因此,在本例中,我想映射'决策树识别的正则表达式输入'和'签出订单输入'。

想要的地图,应该是这样的

want = {0: False,
1: True,
2: False,
3: False,
4: True,
5: False}

我使用循环做了下面的map,我想知道是否有方法使用pandas库。

mapi = []
for i in np.arange(s.shape[0]):
if 'input' in s.iloc[i] and 'unexpected' not in s.iloc[i]:
if 'unexpected' in s.iloc[i-1]:
mapi.append(True)
else:
mapi.append(False)
else:
mapi.append(False)

使用Series.str.contains与移位的Series.shift链接:

s = pd.Series(s)
m = s.str.contains('unexpected')
d = ((s.str.contains('input') & ~m) & m.shift(fill_value=False)).to_dict()
print (d)
{0: False, 1: True, 2: False, 3: False, 4: True, 5: False}

工作原理:

m = s.str.contains('unexpected')
print (pd.concat([s.str.contains('input'),
s.str.contains('unexpected'),
m.shift(fill_value=False),
(s.str.contains('input') & ~m),
((s.str.contains('input') & ~m) & m.shift(fill_value=False))], 
axis=1,
keys=['input','unexpected','shifted','both','final']))
input  unexpected  shifted   both  final
0  False        True    False  False  False
1   True       False     True   True   True
2   True       False    False   True  False
3  False        True    False  False  False
4   True       False     True   True   True
5   True       False    False   True  False

最新更新