在列中搜索字符串,并通过在熊猫的数据框中添加另一列来提及字符串

时间:2018-11-29 09:09:33

标签: pandas

在我的数据中,我有几列。在这些列之一中,我想搜索三个不同的字符串。找到这些字符串后,我需要提及通过在数据中添加另一列并提供一些我们已识别出的名称来建立字符串的行。

我的数据就像 我要执行的数据中的这一列

SaveEmployee() {
            let employeeAge= 0;
         this.employeeService.getAge(this.employeeId).subscribe(data => {
                employeeAge= data;
                if(employeeAge >18) {
              //some logic Code comes here
            } else {
              //some other logic Code comes here
          }
                 }); 

        }

和输出想要像

Campaign      
  Polestar - Remarketing - DN - BGLR
  Promenade - Remarketing - BLR
  Polestar -
  Polestar -BLR
  Urbana-Display-GSP-UK-July

我想在广告系列表中找到字符串REM,Remarketing,GSP,并在名为REM的新列中提及并确定这些行都具有该字符串

  

REM,再营销应提及   再营销GSP想要提及邮件

2 个答案:

答案 0 :(得分:1)

使用:

df = pd.DataFrame({'Campaign':['Polestar - Remarketing - DN - BGLR',
                               'Promenade - Remarketing - BLR',
                              'Polestar -',
                              'Polestar -BLR',
                              'Urbana-Display-GSP-UK-July']})

df['REM'] = '-'
df.iloc[df[df.Campaign.str.contains('Remarketing|REM')].index,1] = 'Remarket'
df.iloc[df[df.Campaign.str.contains('GSP')].index,1] = 'Mail'

df

#     Campaign                            REM
# 0 Polestar - Remarketing - DN - BGLR    Remarket
# 1 Promenade - Remarketing - BLR         Remarket
# 2 Polestar -                            -
# 3 Polestar -BLR                         -
# 4 Urbana-Display-GSP-UK-July            Mail

答案 1 :(得分:0)

使用np.select()的速度略高于上述解决方案。

c1 = df.Campaign.str.contains("Remarketing|REM")
c2 = df.Campaign.str.contains("GSP")
df['REM'] = np.select([c1, c2], ['Remarket', 'Mail'],'-')
#1.07 ms ± 75.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
print(df)

输出:

                             Campaign       REM
0  Polestar - Remarketing - DN - BGLR  Remarket
1       Promenade - Remarketing - BLR  Remarket
2                          Polestar -         -
3                       Polestar -BLR         -
4          Urbana-Display-GSP-UK-July      Mail