【问题标题】:applying lambda row on multiple columns pandas在多列熊猫上应用 lambda 行
【发布时间】:2018-12-07 09:01:35
【问题描述】:

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

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')

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

【问题讨论】:

    标签: python pandas dataframe if-statement lambda


    【解决方案1】:

    你需要使用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 返回一个布尔系列,告诉 numpy.where 是选择第二个还是第三个参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2022-10-20
      • 2020-08-20
      相关资源
      最近更新 更多