为什么我的 Pandas 'apply' 函数不能引用多列? [英] Why isn't my Pandas 'apply' function referencing multiple columns working?

查看:35
本文介绍了为什么我的 Pandas 'apply' 函数不能引用多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用具有以下数据框的多列时,Pandas apply 函数存在一些问题

I have some problems with the Pandas apply function, when using multiple columns with the following dataframe

df = DataFrame ({'a' : np.random.randn(6),
                 'b' : ['foo', 'bar'] * 3,
                 'c' : np.random.randn(6)})

和下面的函数

def my_test(a, b):
    return a % b

当我尝试应用此函数时:

When I try to apply this function with :

df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1)

我收到错误消息:

NameError: ("global name 'a' is not defined", u'occurred at index 0')

我不明白这条消息,我正确定义了名称.

I do not understand this message, I defined the name properly.

我非常感谢您对此问题的任何帮助

I would highly appreciate any help on this issue

更新

感谢您的帮助.我确实在代码中犯了一些语法错误,索引应该放在''.但是我仍然使用更复杂的函数遇到同样的问题,例如:

Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as:

def my_test(a):
    cum_diff = 0
    for ix in df.index():
        cum_diff = cum_diff + (a - df['a'][ix])
    return cum_diff 

推荐答案

您似乎忘记了字符串的 ''.

Seems you forgot the '' of your string.

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

顺便说一句,在我看来,以下方式更优雅:

BTW, in my opinion, following way is more elegant:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

这篇关于为什么我的 Pandas 'apply' 函数不能引用多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆