我创建的示例数据框为:
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')
如何在不定义函数的情况下使其工作。
答案 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
是选择第二个参数还是第三个参数。