将lambda行应用于多列熊猫

时间:2018-06-28 10:09:19

标签: python pandas lambda multiple-columns

我创建的示例数据框为:

tp=pd.DataFrame({'source':['a','s','f'], 
                                'target':['b','n','m'], 
                                'count':[0,8,4]})

并根据'target'列>>的条件创建与源相同的列'col',如果匹配条件,则为默认值,如下所示:

tp['col']=tp.apply(lambda row:row['source'] if row['target'] in ['b','n'] else 'x')

但这会抛出错误:KeyError: ('target', 'occurred at index count')

如何在不定义函数的情况下使其工作。

1 个答案:

答案 0 :(得分:2)

根据@Zero的注释,您需要使用axis=1来告诉熊猫您要对每行应用一个函数。默认值为axis=0

tp['col'] = tp.apply(lambda row: row['source'] if row['target'] in ['b', 'n'] else 'x',
                     axis=1)

但是,对于此特定任务,应使用向量化操作。例如,使用numpy.where

tp['col'] = np.where(tp['target'].isin(['b', 'n']), tp['source'], 'x')

pd.Series.isin返回一个布尔序列,该布尔序列告诉numpy.where是选择第二个参数还是第三个参数。

相关问题