Lambda - 在pandas数据帧上应用组合

时间:2017-04-12 16:19:02

标签: python python-2.7 python-3.x pandas lambda

从以下数据框开始:

enter image description here

我创建了以下功能:

def campaign_name(name,ID,prefix):
    campaign = "S[" + prefix + ID + "]: " + name
    return campaign

我想在像这样的数据框中使用它:

keywords_merge_temporary["campaign name"] = keywords_merge_temporary.apply(lambda x: campaign_name(x.name,x.id,x.prefix), axis=1)

出现问题,由于某种原因,我得到以下错误,这是我过去从未使用过的这种lambda +应用组合的错误:

<ipython-input-...> in <module>()
----> 1 keywords_merge_temporary["campaign name"] = keywords_merge_temporary.apply(lambda z: campaign_name(z.name,z.id,z.prefix), axis=1)

/Users/anaconda/lib/python3.5/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)    4150  if reduce is None:    4151                         reduce = True
-> 4152                     return self._apply_standard(f, axis, reduce=reduce)    4153             else:    4154                 return self._apply_broadcast(f, axis)

/Users/anaconda/lib/python3.5/site-packages/pandas/core/frame.py in
_apply_standard(self, func, axis, ignore_failures, reduce)    4246             try:    4247                 for i, v in enumerate(series_gen):
-> 4248                     results[i] = func(v)    4249                     keys.append(v.name)    4250             except Exception as e:

<ipython-input-...> in <lambda>(z)
----> 1 keywords_merge_temporary["campaign name"] = keywords_merge_temporary.apply(lambda z: campaign_name(z.name,z.id,z.prefix), axis=1)

<ipython-input-52-f727ebf9b9ee> in campaign_name(name, ID, prefix)
      1 def campaign_name(name,ID,prefix):
----> 2     campaign = "S[" + prefix + ID + "]: " + name
      3     return campaign

TypeError: ("ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')", 'occurred at index 0')

0 个答案:

没有答案