2012-09-26 3 views
1

팬더에서 df.apply() 함수를 사용하려고하는데 다음 오류가 발생합니다.'df.apply'함수를 호출하는 동안 python pandas unbound 로컬 오류가 발생했습니다.

df.apply(discardValueLessThan, args=(0.1,))

방법을 당신이 그것을하고 있어요 :이 기능은 당신이 이런 식으로 호출해야 '임계'

from pandas import * 
import numpy as np 
def discardValueLessThan(x, threshold): 
    if x < threshold : return 0 
    else: return x 

df = DataFrame(np.random.randn(8, 3), columns=['A', 'B', 'C']) 

>>> df 
      A   B   C 
0 -1.389871 1.362458 1.531723 
1 -1.200067 -1.114360 -0.020958 
2 -0.064653 0.426051 1.856164 
3 1.103067 0.194196 0.077709 
4 2.675069 -0.848347 0.152521 
5 -0.773200 -0.712175 -0.022908 
6 -0.796237 0.016256 0.390068 
7 -0.413894 0.190118 -0.521194 

df.apply(discardValueLessThan, 0.1) 

>>> df.apply(discardValueLessThan, 0.1) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/pandas-0.8.1-py2.7-macosx-10.5-x86_64.egg/pandas/core/frame.py", line 3576, in apply 
    return self._apply_standard(f, axis) 
    File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/pandas-0.8.1-py2.7-macosx-10.5-x86_64.egg/pandas/core/frame.py", line 3637, in _apply_standard 
    e.args = e.args + ('occurred at index %s' % str(k),) 
UnboundLocalError: local variable 'k' referenced before assignment 

답변

2

오류 메시지는 pandas 버그와 비슷하지만 다른 두 가지 문제가 있다고 생각합니다.

먼저 명명 된 매개 변수를 지정하거나 args을 사용하여 apply에 추가 인수를 전달해야한다고 생각합니다. 두 번째 인수는 아마도 축으로 해석됩니다. 당신이

df.apply(discardValueLessThan, args=(0.1,)) 

또는

df.apply(discardValueLessThan, threshold=0.1) 

를 사용한다면 당신은 그것을 전체 시리즈 물체에 작용, elementwise 행동하지 않는

ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', 'occurred at index A') 

apply 때문에를 얻을 수 있습니다. 다른 방법은 applymap 또는 부울 인덱싱을 포함하여, 즉

In [47]: df = DataFrame(np.random.randn(3, 3), columns=['A', 'B', 'C']) 

In [48]: df 
Out[48]: 
      A   B   C 
0 -0.135336 -0.274687 1.480949 
1 -1.079800 -0.618610 -0.321235 
2 -0.610420 -0.422112 0.102703 

In [49]: df1 = df.applymap(lambda x: discardValueLessThan(x, 0.1)) 

In [50]: df1 
Out[50]: 
    A B   C 
0 0 0 1.480949 
1 0 0 0.000000 
2 0 0 0.102703 

하거나

In [51]: df[df < 0.1] = 0 

In [52]: df 
Out[52]: 
    A B   C 
0 0 0 1.480949 
1 0 0 0.000000 
2 0 0 0.102703 
+0

축 그래서 0.1 실제로 축으로 해석되는 제 2 파라미터이다. 축이 0 또는 1이 아닌 경우보다 유익한 오류 메시지를 마스터하도록 방금 진행했습니다. –

+0

@ChangShe : 예, 내가 생각한 버그는 Throw 될 예외가 아니었을 때 NameError를 잡으려고하는 누군가였습니다 . – DSM

0

보다 작 으면 0으로 모든 항목을 변환하려고 0.1은 discardValueLessThan에 인수로 전달되지 않습니다.

관련 문제