Python 如何根据数据帧中的列条件应用函数

Python 如何根据数据帧中的列条件应用函数,python,pandas,Python,Pandas,我试图在数据帧中的一列上应用函数,如果其中一列,即df['mask']包含False,则应跳过该行。掩码列为布尔类型 这是我的职责 def dates(inp): temp = inp parser = CommonRegex() inp = inp.apply(parser.dates).str.join(', ') return np.where(inp.apply(parser.dates).str.len() ==

我试图在数据帧中的一列上应用函数,如果其中一列,即df['mask']包含False,则应跳过该行。掩码列为布尔类型

这是我的职责

     def dates(inp):
        temp = inp
        parser = CommonRegex()
        inp = inp.apply(parser.dates).str.join(', ')
        return np.where(inp.apply(parser.dates).str.len() == 0, temp, 'X' * random.randrange(3, 8)) 
这是我申请的

      df1.assign(**df1['Dates'].apply(dates).where(df1['mask']== TRUE))
它的投掷错误

         32     temp = inp
         33     parser = CommonRegex()
    ---> 34     inp = inp.apply(parser.dates).str.join(', ')
         35     return np.where(inp.apply(parser.dates).str.len() == 0, temp, 'X' * random.randrange(3, 8))
         36 

    AttributeError: 'Timestamp' object has no attribute 'apply'    
这是我的数据框

         Name     |  Dates   |  mask |
         ..............................
         Tom      | 21/02/2018| True
         Nick     | 28/07/2018| False
         Juli     | 11/08/2018| True
         June     | 01/02/2018| True
         XHGM     | 07/08/2018| False   
我试图以这种方式获得输出,对于false值,它应该跳过,对于true值,它应该调用date函数并隐藏数据值

         Name     |  Dates   |  mask |
         ..............................
         Tom      | XXXXX     | True
         Nick     |28/07/2018 | False
         Juli     | XXXXX     | True
         June     | XXXXX     | True
         XHGM     | 07/08/2018| False     
用于传递要运行的列,也可使用“按掩码”筛选行,以及用于指定列名:

df1.loc[df1['mask'], 'Dates'] = df1.loc[df1['mask'], 'Dates'].pipe(dates)
print (df1)
   Name       Dates   mask
0   Tom         XXX   True
1  Nick  28/07/2018  False
2  Juli         XXX   True
3  June         XXX   True
4  XHGM  07/08/2018  False
使用
assign
的解决方案也是可行的,但缺点是函数按所有值循环,然后进行过滤,因此,如果大型
Dataframe
中只有很少的
True
s值,则速度应较慢:

df1 = df1.assign(Dates = np.where(df1['mask'], df1['Dates'].pipe(dates), df1['Dates']))

hey@jezrael它抛出错误预期字符串或字节,如object@ParthTiwari-如果出现相同错误,您能否仅使用问题中的样本数据进行测试?