为什么我的Pandas“apply”函数不能引用多个列?

2024-04-23 17:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

以及以下功能

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

当我尝试应用此函数时:

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

我不明白这个消息,我正确地定义了这个名字。

我非常感谢你在这个问题上的帮助

更新

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

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

Tags: 函数test消息dfindexreturnmydef
3条回答

假设我们要将add5函数应用于DataFrame df的列“a”和“b”

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

似乎你忘了你的字符串''

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

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

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

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

如果您只想计算(a列)%(b列),则不需要apply,直接计算即可:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

相关问题 更多 >