我正在尝试在 pandas 中使用 df.apply() 函数,但出现以下错误。如果小于“阈值”,该函数会尝试将每个条目转换为 0
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