mun*_*uni 6 python lambda if-statement dataframe pandas
我正在创建一个示例数据框:
tp = pd.DataFrame({'source':['a','s','f'],
'target':['b','n','m'],
'count':[0,8,4]})
Run Code Online (Sandbox Code Playgroud)
并根据“目标”列的条件创建列“col”>>与源相同,如果匹配条件,则为默认值,如下所示:
tp['col'] = tp.apply(lambda row:row['source'] if row['target'] in ['b','n'] else 'x')
Run Code Online (Sandbox Code Playgroud)
但它给我这个错误: KeyError: ('target', 'occurred at index count')
如何在不定义函数的情况下使其工作?
您需要使用axis=1来告诉 Pandas 您要对每一行应用一个函数。默认值为axis=0.
tp['col'] = tp.apply(lambda row: row['source'] if row['target'] in ['b', 'n'] else 'x',
axis=1)
Run Code Online (Sandbox Code Playgroud)
但是,对于此特定任务,您应该使用矢量化操作。例如,使用numpy.where:
tp['col'] = np.where(tp['target'].isin(['b', 'n']), tp['source'], 'x')
Run Code Online (Sandbox Code Playgroud)
pd.Series.isin返回一个布尔系列,它告诉您numpy.where是选择第二个还是第三个参数。