gpt4 book ai didi

python - 在多列 Pandas 上应用 lambda 行

转载 作者:行者123 更新时间:2023-12-03 16:04:39 25 4
gpt4 key购买 nike

我正在创建一个示例数据框:

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

并根据“目标”列的条件创建列“col”>>与源相同,如果匹配条件,则为默认值,如下所示:
tp['col'] = tp.apply(lambda row:row['source'] if row['target'] in ['b','n'] else 'x')

但这给我带来了这个错误: 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)

但是,对于此特定任务,您应该使用矢量化操作。例如,使用 numpy.where :
tp['col'] = np.where(tp['target'].isin(['b', 'n']), tp['source'], 'x')
pd.Series.isin 返回一个 bool 系列,它告诉 numpy.where是选择第二个还是第三个参数。

关于python - 在多列 Pandas 上应用 lambda 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com