代码之家  ›  专栏  ›  技术社区  ›  kms

在条件为:序列的真值不明确的情况下,将函数应用于每一行

  •  0
  • kms  · 技术社区  · 4 年前
    df = pd.DataFrame({'id': [1,2,3],
                       'img': ['x',0,'x']
                     })
    
    def details(id):
    
        return 2
    
    df['new_col'] = df['img'].apply(lambda x: details(x['id']) if x == 0 else x, axis=1)
    

    我只想将函数应用于行,其中单元格值==0。当我运行上述行时,我得到以下错误:

       ~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __nonzero__(self)
       1327 
       1328     def __nonzero__(self):
    -> 1329         raise ValueError(
       1330             f"The truth value of a {type(self).__name__} is ambiguous. "
       1331             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
    
    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   I'mahdi    4 年前

    试试这个:

    df = pd.DataFrame({'id': [1,2,3],
                       'img': ['x',0,'x']
                     })
    
    def details(id):
        return 2
    
    df['new_col'] = df.apply(lambda row: details(row['id']) if row['img'] == 0 else row['img'], axis=1)
    
        2
  •  0
  •   kms    4 年前

    是的,mre是不可复制的。

    不过,以下是我如何让它发挥作用的:

    # Read Pandas DataFrame 
    
    df['img'] = df.apply(lambda x: details(x['id']) if type(x['img']) == int else x['img'], axis=1)