【问题标题】:Check for previous value condition, and grabbing sucessor value with condition检查前值条件,并抓取有条件的后继值
【发布时间】:2023-01-19 21:58:25
【问题描述】:

我有以下示例系列

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'}

我想要做的是获取“意外”关键字字符串下的值,并在其中包含“输入”字符串。因此,例如,如果我有“反馈评级-正面-意外来源”,并且下一个值包含“输入”字符串。地图标记为 True。 所以在这种情况下,我想映射“决策树识别正则表达式输入”和“结帐订单输入”。

想要的地图,会是这样的

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

我使用循环做了下面的地图,我想知道是否有使用 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)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用 Series.str.containsSeries.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
    

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2021-10-29
      • 2021-05-07
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多